]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/f32.rs
Rollup merge of #103221 - TaKO8Ki:fix-103202, r=oli-obk
[rust.git] / library / core / src / num / f32.rs
1 //! Constants for the `f32` single-precision floating point type.
2 //!
3 //! *[See also the `f32` primitive type][f32].*
4 //!
5 //! Mathematically significant numbers are provided in the `consts` sub-module.
6 //!
7 //! For the constants defined directly in this module
8 //! (as distinct from those defined in the `consts` sub-module),
9 //! new code should instead use the associated constants
10 //! defined directly on the `f32` type.
11
12 #![stable(feature = "rust1", since = "1.0.0")]
13
14 use crate::convert::FloatToInt;
15 #[cfg(not(test))]
16 use crate::intrinsics;
17 use crate::mem;
18 use crate::num::FpCategory;
19
20 /// The radix or base of the internal representation of `f32`.
21 /// Use [`f32::RADIX`] instead.
22 ///
23 /// # Examples
24 ///
25 /// ```rust
26 /// // deprecated way
27 /// # #[allow(deprecated, deprecated_in_future)]
28 /// let r = std::f32::RADIX;
29 ///
30 /// // intended way
31 /// let r = f32::RADIX;
32 /// ```
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[deprecated(since = "TBD", note = "replaced by the `RADIX` associated constant on `f32`")]
35 pub const RADIX: u32 = f32::RADIX;
36
37 /// Number of significant digits in base 2.
38 /// Use [`f32::MANTISSA_DIGITS`] instead.
39 ///
40 /// # Examples
41 ///
42 /// ```rust
43 /// // deprecated way
44 /// # #[allow(deprecated, deprecated_in_future)]
45 /// let d = std::f32::MANTISSA_DIGITS;
46 ///
47 /// // intended way
48 /// let d = f32::MANTISSA_DIGITS;
49 /// ```
50 #[stable(feature = "rust1", since = "1.0.0")]
51 #[deprecated(
52     since = "TBD",
53     note = "replaced by the `MANTISSA_DIGITS` associated constant on `f32`"
54 )]
55 pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
56
57 /// Approximate number of significant digits in base 10.
58 /// Use [`f32::DIGITS`] instead.
59 ///
60 /// # Examples
61 ///
62 /// ```rust
63 /// // deprecated way
64 /// # #[allow(deprecated, deprecated_in_future)]
65 /// let d = std::f32::DIGITS;
66 ///
67 /// // intended way
68 /// let d = f32::DIGITS;
69 /// ```
70 #[stable(feature = "rust1", since = "1.0.0")]
71 #[deprecated(since = "TBD", note = "replaced by the `DIGITS` associated constant on `f32`")]
72 pub const DIGITS: u32 = f32::DIGITS;
73
74 /// [Machine epsilon] value for `f32`.
75 /// Use [`f32::EPSILON`] instead.
76 ///
77 /// This is the difference between `1.0` and the next larger representable number.
78 ///
79 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
80 ///
81 /// # Examples
82 ///
83 /// ```rust
84 /// // deprecated way
85 /// # #[allow(deprecated, deprecated_in_future)]
86 /// let e = std::f32::EPSILON;
87 ///
88 /// // intended way
89 /// let e = f32::EPSILON;
90 /// ```
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f32`")]
93 pub const EPSILON: f32 = f32::EPSILON;
94
95 /// Smallest finite `f32` value.
96 /// Use [`f32::MIN`] instead.
97 ///
98 /// # Examples
99 ///
100 /// ```rust
101 /// // deprecated way
102 /// # #[allow(deprecated, deprecated_in_future)]
103 /// let min = std::f32::MIN;
104 ///
105 /// // intended way
106 /// let min = f32::MIN;
107 /// ```
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f32`")]
110 pub const MIN: f32 = f32::MIN;
111
112 /// Smallest positive normal `f32` value.
113 /// Use [`f32::MIN_POSITIVE`] instead.
114 ///
115 /// # Examples
116 ///
117 /// ```rust
118 /// // deprecated way
119 /// # #[allow(deprecated, deprecated_in_future)]
120 /// let min = std::f32::MIN_POSITIVE;
121 ///
122 /// // intended way
123 /// let min = f32::MIN_POSITIVE;
124 /// ```
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f32`")]
127 pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
128
129 /// Largest finite `f32` value.
130 /// Use [`f32::MAX`] instead.
131 ///
132 /// # Examples
133 ///
134 /// ```rust
135 /// // deprecated way
136 /// # #[allow(deprecated, deprecated_in_future)]
137 /// let max = std::f32::MAX;
138 ///
139 /// // intended way
140 /// let max = f32::MAX;
141 /// ```
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f32`")]
144 pub const MAX: f32 = f32::MAX;
145
146 /// One greater than the minimum possible normal power of 2 exponent.
147 /// Use [`f32::MIN_EXP`] instead.
148 ///
149 /// # Examples
150 ///
151 /// ```rust
152 /// // deprecated way
153 /// # #[allow(deprecated, deprecated_in_future)]
154 /// let min = std::f32::MIN_EXP;
155 ///
156 /// // intended way
157 /// let min = f32::MIN_EXP;
158 /// ```
159 #[stable(feature = "rust1", since = "1.0.0")]
160 #[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f32`")]
161 pub const MIN_EXP: i32 = f32::MIN_EXP;
162
163 /// Maximum possible power of 2 exponent.
164 /// Use [`f32::MAX_EXP`] instead.
165 ///
166 /// # Examples
167 ///
168 /// ```rust
169 /// // deprecated way
170 /// # #[allow(deprecated, deprecated_in_future)]
171 /// let max = std::f32::MAX_EXP;
172 ///
173 /// // intended way
174 /// let max = f32::MAX_EXP;
175 /// ```
176 #[stable(feature = "rust1", since = "1.0.0")]
177 #[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f32`")]
178 pub const MAX_EXP: i32 = f32::MAX_EXP;
179
180 /// Minimum possible normal power of 10 exponent.
181 /// Use [`f32::MIN_10_EXP`] instead.
182 ///
183 /// # Examples
184 ///
185 /// ```rust
186 /// // deprecated way
187 /// # #[allow(deprecated, deprecated_in_future)]
188 /// let min = std::f32::MIN_10_EXP;
189 ///
190 /// // intended way
191 /// let min = f32::MIN_10_EXP;
192 /// ```
193 #[stable(feature = "rust1", since = "1.0.0")]
194 #[deprecated(since = "TBD", note = "replaced by the `MIN_10_EXP` associated constant on `f32`")]
195 pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
196
197 /// Maximum possible power of 10 exponent.
198 /// Use [`f32::MAX_10_EXP`] instead.
199 ///
200 /// # Examples
201 ///
202 /// ```rust
203 /// // deprecated way
204 /// # #[allow(deprecated, deprecated_in_future)]
205 /// let max = std::f32::MAX_10_EXP;
206 ///
207 /// // intended way
208 /// let max = f32::MAX_10_EXP;
209 /// ```
210 #[stable(feature = "rust1", since = "1.0.0")]
211 #[deprecated(since = "TBD", note = "replaced by the `MAX_10_EXP` associated constant on `f32`")]
212 pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
213
214 /// Not a Number (NaN).
215 /// Use [`f32::NAN`] instead.
216 ///
217 /// # Examples
218 ///
219 /// ```rust
220 /// // deprecated way
221 /// # #[allow(deprecated, deprecated_in_future)]
222 /// let nan = std::f32::NAN;
223 ///
224 /// // intended way
225 /// let nan = f32::NAN;
226 /// ```
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f32`")]
229 pub const NAN: f32 = f32::NAN;
230
231 /// Infinity (∞).
232 /// Use [`f32::INFINITY`] instead.
233 ///
234 /// # Examples
235 ///
236 /// ```rust
237 /// // deprecated way
238 /// # #[allow(deprecated, deprecated_in_future)]
239 /// let inf = std::f32::INFINITY;
240 ///
241 /// // intended way
242 /// let inf = f32::INFINITY;
243 /// ```
244 #[stable(feature = "rust1", since = "1.0.0")]
245 #[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f32`")]
246 pub const INFINITY: f32 = f32::INFINITY;
247
248 /// Negative infinity (−∞).
249 /// Use [`f32::NEG_INFINITY`] instead.
250 ///
251 /// # Examples
252 ///
253 /// ```rust
254 /// // deprecated way
255 /// # #[allow(deprecated, deprecated_in_future)]
256 /// let ninf = std::f32::NEG_INFINITY;
257 ///
258 /// // intended way
259 /// let ninf = f32::NEG_INFINITY;
260 /// ```
261 #[stable(feature = "rust1", since = "1.0.0")]
262 #[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f32`")]
263 pub const NEG_INFINITY: f32 = f32::NEG_INFINITY;
264
265 /// Basic mathematical constants.
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub mod consts {
268     // FIXME: replace with mathematical constants from cmath.
269
270     /// Archimedes' constant (π)
271     #[stable(feature = "rust1", since = "1.0.0")]
272     pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
273
274     /// The full circle constant (τ)
275     ///
276     /// Equal to 2π.
277     #[stable(feature = "tau_constant", since = "1.47.0")]
278     pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
279
280     /// π/2
281     #[stable(feature = "rust1", since = "1.0.0")]
282     pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
283
284     /// π/3
285     #[stable(feature = "rust1", since = "1.0.0")]
286     pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
287
288     /// π/4
289     #[stable(feature = "rust1", since = "1.0.0")]
290     pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
291
292     /// π/6
293     #[stable(feature = "rust1", since = "1.0.0")]
294     pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
295
296     /// π/8
297     #[stable(feature = "rust1", since = "1.0.0")]
298     pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
299
300     /// 1/π
301     #[stable(feature = "rust1", since = "1.0.0")]
302     pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
303
304     /// 2/π
305     #[stable(feature = "rust1", since = "1.0.0")]
306     pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
307
308     /// 2/sqrt(π)
309     #[stable(feature = "rust1", since = "1.0.0")]
310     pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
311
312     /// sqrt(2)
313     #[stable(feature = "rust1", since = "1.0.0")]
314     pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
315
316     /// 1/sqrt(2)
317     #[stable(feature = "rust1", since = "1.0.0")]
318     pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
319
320     /// Euler's number (e)
321     #[stable(feature = "rust1", since = "1.0.0")]
322     pub const E: f32 = 2.71828182845904523536028747135266250_f32;
323
324     /// log<sub>2</sub>(e)
325     #[stable(feature = "rust1", since = "1.0.0")]
326     pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
327
328     /// log<sub>2</sub>(10)
329     #[stable(feature = "extra_log_consts", since = "1.43.0")]
330     pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
331
332     /// log<sub>10</sub>(e)
333     #[stable(feature = "rust1", since = "1.0.0")]
334     pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
335
336     /// log<sub>10</sub>(2)
337     #[stable(feature = "extra_log_consts", since = "1.43.0")]
338     pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
339
340     /// ln(2)
341     #[stable(feature = "rust1", since = "1.0.0")]
342     pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
343
344     /// ln(10)
345     #[stable(feature = "rust1", since = "1.0.0")]
346     pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
347 }
348
349 #[cfg(not(test))]
350 impl f32 {
351     /// The radix or base of the internal representation of `f32`.
352     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
353     pub const RADIX: u32 = 2;
354
355     /// Number of significant digits in base 2.
356     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
357     pub const MANTISSA_DIGITS: u32 = 24;
358
359     /// Approximate number of significant digits in base 10.
360     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
361     pub const DIGITS: u32 = 6;
362
363     /// [Machine epsilon] value for `f32`.
364     ///
365     /// This is the difference between `1.0` and the next larger representable number.
366     ///
367     /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
368     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
369     pub const EPSILON: f32 = 1.19209290e-07_f32;
370
371     /// Smallest finite `f32` value.
372     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
373     pub const MIN: f32 = -3.40282347e+38_f32;
374     /// Smallest positive normal `f32` value.
375     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
376     pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
377     /// Largest finite `f32` value.
378     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
379     pub const MAX: f32 = 3.40282347e+38_f32;
380
381     /// One greater than the minimum possible normal power of 2 exponent.
382     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
383     pub const MIN_EXP: i32 = -125;
384     /// Maximum possible power of 2 exponent.
385     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
386     pub const MAX_EXP: i32 = 128;
387
388     /// Minimum possible normal power of 10 exponent.
389     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
390     pub const MIN_10_EXP: i32 = -37;
391     /// Maximum possible power of 10 exponent.
392     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
393     pub const MAX_10_EXP: i32 = 38;
394
395     /// Not a Number (NaN).
396     ///
397     /// Note that IEEE 754 doesn't define just a single NaN value;
398     /// a plethora of bit patterns are considered to be NaN.
399     /// Furthermore, the standard makes a difference
400     /// between a "signaling" and a "quiet" NaN,
401     /// and allows inspecting its "payload" (the unspecified bits in the bit pattern).
402     /// This constant isn't guaranteed to equal to any specific NaN bitpattern,
403     /// and the stability of its representation over Rust versions
404     /// and target platforms isn't guaranteed.
405     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
406     pub const NAN: f32 = 0.0_f32 / 0.0_f32;
407     /// Infinity (∞).
408     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
409     pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
410     /// Negative infinity (−∞).
411     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
412     pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
413
414     /// Returns `true` if this value is NaN.
415     ///
416     /// ```
417     /// let nan = f32::NAN;
418     /// let f = 7.0_f32;
419     ///
420     /// assert!(nan.is_nan());
421     /// assert!(!f.is_nan());
422     /// ```
423     #[must_use]
424     #[stable(feature = "rust1", since = "1.0.0")]
425     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
426     #[inline]
427     pub const fn is_nan(self) -> bool {
428         self != self
429     }
430
431     // FIXME(#50145): `abs` is publicly unavailable in libcore due to
432     // concerns about portability, so this implementation is for
433     // private use internally.
434     #[inline]
435     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
436     pub(crate) const fn abs_private(self) -> f32 {
437         // SAFETY: This transmutation is fine. Probably. For the reasons std is using it.
438         unsafe { mem::transmute::<u32, f32>(mem::transmute::<f32, u32>(self) & 0x7fff_ffff) }
439     }
440
441     /// Returns `true` if this value is positive infinity or negative infinity, and
442     /// `false` otherwise.
443     ///
444     /// ```
445     /// let f = 7.0f32;
446     /// let inf = f32::INFINITY;
447     /// let neg_inf = f32::NEG_INFINITY;
448     /// let nan = f32::NAN;
449     ///
450     /// assert!(!f.is_infinite());
451     /// assert!(!nan.is_infinite());
452     ///
453     /// assert!(inf.is_infinite());
454     /// assert!(neg_inf.is_infinite());
455     /// ```
456     #[must_use]
457     #[stable(feature = "rust1", since = "1.0.0")]
458     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
459     #[inline]
460     pub const fn is_infinite(self) -> bool {
461         // Getting clever with transmutation can result in incorrect answers on some FPUs
462         // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
463         // See https://github.com/rust-lang/rust/issues/72327
464         (self == f32::INFINITY) | (self == f32::NEG_INFINITY)
465     }
466
467     /// Returns `true` if this number is neither infinite nor NaN.
468     ///
469     /// ```
470     /// let f = 7.0f32;
471     /// let inf = f32::INFINITY;
472     /// let neg_inf = f32::NEG_INFINITY;
473     /// let nan = f32::NAN;
474     ///
475     /// assert!(f.is_finite());
476     ///
477     /// assert!(!nan.is_finite());
478     /// assert!(!inf.is_finite());
479     /// assert!(!neg_inf.is_finite());
480     /// ```
481     #[must_use]
482     #[stable(feature = "rust1", since = "1.0.0")]
483     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
484     #[inline]
485     pub const fn is_finite(self) -> bool {
486         // There's no need to handle NaN separately: if self is NaN,
487         // the comparison is not true, exactly as desired.
488         self.abs_private() < Self::INFINITY
489     }
490
491     /// Returns `true` if the number is [subnormal].
492     ///
493     /// ```
494     /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
495     /// let max = f32::MAX;
496     /// let lower_than_min = 1.0e-40_f32;
497     /// let zero = 0.0_f32;
498     ///
499     /// assert!(!min.is_subnormal());
500     /// assert!(!max.is_subnormal());
501     ///
502     /// assert!(!zero.is_subnormal());
503     /// assert!(!f32::NAN.is_subnormal());
504     /// assert!(!f32::INFINITY.is_subnormal());
505     /// // Values between `0` and `min` are Subnormal.
506     /// assert!(lower_than_min.is_subnormal());
507     /// ```
508     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
509     #[must_use]
510     #[stable(feature = "is_subnormal", since = "1.53.0")]
511     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
512     #[inline]
513     pub const fn is_subnormal(self) -> bool {
514         matches!(self.classify(), FpCategory::Subnormal)
515     }
516
517     /// Returns `true` if the number is neither zero, infinite,
518     /// [subnormal], or NaN.
519     ///
520     /// ```
521     /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
522     /// let max = f32::MAX;
523     /// let lower_than_min = 1.0e-40_f32;
524     /// let zero = 0.0_f32;
525     ///
526     /// assert!(min.is_normal());
527     /// assert!(max.is_normal());
528     ///
529     /// assert!(!zero.is_normal());
530     /// assert!(!f32::NAN.is_normal());
531     /// assert!(!f32::INFINITY.is_normal());
532     /// // Values between `0` and `min` are Subnormal.
533     /// assert!(!lower_than_min.is_normal());
534     /// ```
535     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
536     #[must_use]
537     #[stable(feature = "rust1", since = "1.0.0")]
538     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
539     #[inline]
540     pub const fn is_normal(self) -> bool {
541         matches!(self.classify(), FpCategory::Normal)
542     }
543
544     /// Returns the floating point category of the number. If only one property
545     /// is going to be tested, it is generally faster to use the specific
546     /// predicate instead.
547     ///
548     /// ```
549     /// use std::num::FpCategory;
550     ///
551     /// let num = 12.4_f32;
552     /// let inf = f32::INFINITY;
553     ///
554     /// assert_eq!(num.classify(), FpCategory::Normal);
555     /// assert_eq!(inf.classify(), FpCategory::Infinite);
556     /// ```
557     #[stable(feature = "rust1", since = "1.0.0")]
558     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
559     pub const fn classify(self) -> FpCategory {
560         // A previous implementation tried to only use bitmask-based checks,
561         // using f32::to_bits to transmute the float to its bit repr and match on that.
562         // Unfortunately, floating point numbers can be much worse than that.
563         // This also needs to not result in recursive evaluations of f64::to_bits.
564         //
565         // On some processors, in some cases, LLVM will "helpfully" lower floating point ops,
566         // in spite of a request for them using f32 and f64, to things like x87 operations.
567         // These have an f64's mantissa, but can have a larger than normal exponent.
568         // FIXME(jubilee): Using x87 operations is never necessary in order to function
569         // on x86 processors for Rust-to-Rust calls, so this issue should not happen.
570         // Code generation should be adjusted to use non-C calling conventions, avoiding this.
571         //
572         if self.is_infinite() {
573             // Thus, a value may compare unequal to infinity, despite having a "full" exponent mask.
574             FpCategory::Infinite
575         } else if self.is_nan() {
576             // And it may not be NaN, as it can simply be an "overextended" finite value.
577             FpCategory::Nan
578         } else {
579             // However, std can't simply compare to zero to check for zero, either,
580             // as correctness requires avoiding equality tests that may be Subnormal == -0.0
581             // because it may be wrong under "denormals are zero" and "flush to zero" modes.
582             // Most of std's targets don't use those, but they are used for thumbv7neon.
583             // So, this does use bitpattern matching for the rest.
584
585             // SAFETY: f32 to u32 is fine. Usually.
586             // If classify has gotten this far, the value is definitely in one of these categories.
587             unsafe { f32::partial_classify(self) }
588         }
589     }
590
591     // This doesn't actually return a right answer for NaN on purpose,
592     // seeing as how it cannot correctly discern between a floating point NaN,
593     // and some normal floating point numbers truncated from an x87 FPU.
594     // FIXME(jubilee): This probably could at least answer things correctly for Infinity,
595     // like the f64 version does, but I need to run more checks on how things go on x86.
596     // I fear losing mantissa data that would have answered that differently.
597     //
598     // # Safety
599     // This requires making sure you call this function for values it answers correctly on,
600     // otherwise it returns a wrong answer. This is not important for memory safety per se,
601     // but getting floats correct is important for not accidentally leaking const eval
602     // runtime-deviating logic which may or may not be acceptable.
603     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
604     const unsafe fn partial_classify(self) -> FpCategory {
605         const EXP_MASK: u32 = 0x7f800000;
606         const MAN_MASK: u32 = 0x007fffff;
607
608         // SAFETY: The caller is not asking questions for which this will tell lies.
609         let b = unsafe { mem::transmute::<f32, u32>(self) };
610         match (b & MAN_MASK, b & EXP_MASK) {
611             (0, 0) => FpCategory::Zero,
612             (_, 0) => FpCategory::Subnormal,
613             _ => FpCategory::Normal,
614         }
615     }
616
617     // This operates on bits, and only bits, so it can ignore concerns about weird FPUs.
618     // FIXME(jubilee): In a just world, this would be the entire impl for classify,
619     // plus a transmute. We do not live in a just world, but we can make it more so.
620     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
621     const fn classify_bits(b: u32) -> FpCategory {
622         const EXP_MASK: u32 = 0x7f800000;
623         const MAN_MASK: u32 = 0x007fffff;
624
625         match (b & MAN_MASK, b & EXP_MASK) {
626             (0, EXP_MASK) => FpCategory::Infinite,
627             (_, EXP_MASK) => FpCategory::Nan,
628             (0, 0) => FpCategory::Zero,
629             (_, 0) => FpCategory::Subnormal,
630             _ => FpCategory::Normal,
631         }
632     }
633
634     /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
635     /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any
636     /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
637     /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
638     /// `is_sign_positive` on a NaN might produce an unexpected result in some cases.
639     /// See [explanation of NaN as a special value](f32) for more info.
640     ///
641     /// ```
642     /// let f = 7.0_f32;
643     /// let g = -7.0_f32;
644     ///
645     /// assert!(f.is_sign_positive());
646     /// assert!(!g.is_sign_positive());
647     /// ```
648     #[must_use]
649     #[stable(feature = "rust1", since = "1.0.0")]
650     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
651     #[inline]
652     pub const fn is_sign_positive(self) -> bool {
653         !self.is_sign_negative()
654     }
655
656     /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
657     /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any
658     /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
659     /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
660     /// `is_sign_negative` on a NaN might produce an unexpected result in some cases.
661     /// See [explanation of NaN as a special value](f32) for more info.
662     ///
663     /// ```
664     /// let f = 7.0f32;
665     /// let g = -7.0f32;
666     ///
667     /// assert!(!f.is_sign_negative());
668     /// assert!(g.is_sign_negative());
669     /// ```
670     #[must_use]
671     #[stable(feature = "rust1", since = "1.0.0")]
672     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
673     #[inline]
674     pub const fn is_sign_negative(self) -> bool {
675         // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
676         // applies to zeros and NaNs as well.
677         // SAFETY: This is just transmuting to get the sign bit, it's fine.
678         unsafe { mem::transmute::<f32, u32>(self) & 0x8000_0000 != 0 }
679     }
680
681     /// Returns the least number greater than `self`.
682     ///
683     /// Let `TINY` be the smallest representable positive `f32`. Then,
684     ///  - if `self.is_nan()`, this returns `self`;
685     ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
686     ///  - if `self` is `-TINY`, this returns -0.0;
687     ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
688     ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
689     ///  - otherwise the unique least value greater than `self` is returned.
690     ///
691     /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
692     /// is finite `x == x.next_up().next_down()` also holds.
693     ///
694     /// ```rust
695     /// #![feature(float_next_up_down)]
696     /// // f32::EPSILON is the difference between 1.0 and the next number up.
697     /// assert_eq!(1.0f32.next_up(), 1.0 + f32::EPSILON);
698     /// // But not for most numbers.
699     /// assert!(0.1f32.next_up() < 0.1 + f32::EPSILON);
700     /// assert_eq!(16777216f32.next_up(), 16777218.0);
701     /// ```
702     ///
703     /// [`NEG_INFINITY`]: Self::NEG_INFINITY
704     /// [`INFINITY`]: Self::INFINITY
705     /// [`MIN`]: Self::MIN
706     /// [`MAX`]: Self::MAX
707     #[unstable(feature = "float_next_up_down", issue = "91399")]
708     #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
709     pub const fn next_up(self) -> Self {
710         // We must use strictly integer arithmetic to prevent denormals from
711         // flushing to zero after an arithmetic operation on some platforms.
712         const TINY_BITS: u32 = 0x1; // Smallest positive f32.
713         const CLEAR_SIGN_MASK: u32 = 0x7fff_ffff;
714
715         let bits = self.to_bits();
716         if self.is_nan() || bits == Self::INFINITY.to_bits() {
717             return self;
718         }
719
720         let abs = bits & CLEAR_SIGN_MASK;
721         let next_bits = if abs == 0 {
722             TINY_BITS
723         } else if bits == abs {
724             bits + 1
725         } else {
726             bits - 1
727         };
728         Self::from_bits(next_bits)
729     }
730
731     /// Returns the greatest number less than `self`.
732     ///
733     /// Let `TINY` be the smallest representable positive `f32`. Then,
734     ///  - if `self.is_nan()`, this returns `self`;
735     ///  - if `self` is [`INFINITY`], this returns [`MAX`];
736     ///  - if `self` is `TINY`, this returns 0.0;
737     ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
738     ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
739     ///  - otherwise the unique greatest value less than `self` is returned.
740     ///
741     /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
742     /// is finite `x == x.next_down().next_up()` also holds.
743     ///
744     /// ```rust
745     /// #![feature(float_next_up_down)]
746     /// let x = 1.0f32;
747     /// // Clamp value into range [0, 1).
748     /// let clamped = x.clamp(0.0, 1.0f32.next_down());
749     /// assert!(clamped < 1.0);
750     /// assert_eq!(clamped.next_up(), 1.0);
751     /// ```
752     ///
753     /// [`NEG_INFINITY`]: Self::NEG_INFINITY
754     /// [`INFINITY`]: Self::INFINITY
755     /// [`MIN`]: Self::MIN
756     /// [`MAX`]: Self::MAX
757     #[unstable(feature = "float_next_up_down", issue = "91399")]
758     #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
759     pub const fn next_down(self) -> Self {
760         // We must use strictly integer arithmetic to prevent denormals from
761         // flushing to zero after an arithmetic operation on some platforms.
762         const NEG_TINY_BITS: u32 = 0x8000_0001; // Smallest (in magnitude) negative f32.
763         const CLEAR_SIGN_MASK: u32 = 0x7fff_ffff;
764
765         let bits = self.to_bits();
766         if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
767             return self;
768         }
769
770         let abs = bits & CLEAR_SIGN_MASK;
771         let next_bits = if abs == 0 {
772             NEG_TINY_BITS
773         } else if bits == abs {
774             bits - 1
775         } else {
776             bits + 1
777         };
778         Self::from_bits(next_bits)
779     }
780
781     /// Takes the reciprocal (inverse) of a number, `1/x`.
782     ///
783     /// ```
784     /// let x = 2.0_f32;
785     /// let abs_difference = (x.recip() - (1.0 / x)).abs();
786     ///
787     /// assert!(abs_difference <= f32::EPSILON);
788     /// ```
789     #[must_use = "this returns the result of the operation, without modifying the original"]
790     #[stable(feature = "rust1", since = "1.0.0")]
791     #[inline]
792     pub fn recip(self) -> f32 {
793         1.0 / self
794     }
795
796     /// Converts radians to degrees.
797     ///
798     /// ```
799     /// let angle = std::f32::consts::PI;
800     ///
801     /// let abs_difference = (angle.to_degrees() - 180.0).abs();
802     ///
803     /// assert!(abs_difference <= f32::EPSILON);
804     /// ```
805     #[must_use = "this returns the result of the operation, \
806                   without modifying the original"]
807     #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
808     #[inline]
809     pub fn to_degrees(self) -> f32 {
810         // Use a constant for better precision.
811         const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
812         self * PIS_IN_180
813     }
814
815     /// Converts degrees to radians.
816     ///
817     /// ```
818     /// let angle = 180.0f32;
819     ///
820     /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
821     ///
822     /// assert!(abs_difference <= f32::EPSILON);
823     /// ```
824     #[must_use = "this returns the result of the operation, \
825                   without modifying the original"]
826     #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
827     #[inline]
828     pub fn to_radians(self) -> f32 {
829         let value: f32 = consts::PI;
830         self * (value / 180.0f32)
831     }
832
833     /// Returns the maximum of the two numbers, ignoring NaN.
834     ///
835     /// If one of the arguments is NaN, then the other argument is returned.
836     /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
837     /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
838     /// This also matches the behavior of libm’s fmax.
839     ///
840     /// ```
841     /// let x = 1.0f32;
842     /// let y = 2.0f32;
843     ///
844     /// assert_eq!(x.max(y), y);
845     /// ```
846     #[must_use = "this returns the result of the comparison, without modifying either input"]
847     #[stable(feature = "rust1", since = "1.0.0")]
848     #[inline]
849     pub fn max(self, other: f32) -> f32 {
850         intrinsics::maxnumf32(self, other)
851     }
852
853     /// Returns the minimum of the two numbers, ignoring NaN.
854     ///
855     /// If one of the arguments is NaN, then the other argument is returned.
856     /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
857     /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
858     /// This also matches the behavior of libm’s fmin.
859     ///
860     /// ```
861     /// let x = 1.0f32;
862     /// let y = 2.0f32;
863     ///
864     /// assert_eq!(x.min(y), x);
865     /// ```
866     #[must_use = "this returns the result of the comparison, without modifying either input"]
867     #[stable(feature = "rust1", since = "1.0.0")]
868     #[inline]
869     pub fn min(self, other: f32) -> f32 {
870         intrinsics::minnumf32(self, other)
871     }
872
873     /// Returns the maximum of the two numbers, propagating NaN.
874     ///
875     /// This returns NaN when *either* argument is NaN, as opposed to
876     /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
877     ///
878     /// ```
879     /// #![feature(float_minimum_maximum)]
880     /// let x = 1.0f32;
881     /// let y = 2.0f32;
882     ///
883     /// assert_eq!(x.maximum(y), y);
884     /// assert!(x.maximum(f32::NAN).is_nan());
885     /// ```
886     ///
887     /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
888     /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
889     /// Note that this follows the semantics specified in IEEE 754-2019.
890     ///
891     /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
892     /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
893     #[must_use = "this returns the result of the comparison, without modifying either input"]
894     #[unstable(feature = "float_minimum_maximum", issue = "91079")]
895     #[inline]
896     pub fn maximum(self, other: f32) -> f32 {
897         if self > other {
898             self
899         } else if other > self {
900             other
901         } else if self == other {
902             if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
903         } else {
904             self + other
905         }
906     }
907
908     /// Returns the minimum of the two numbers, propagating NaN.
909     ///
910     /// This returns NaN when *either* argument is NaN, as opposed to
911     /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
912     ///
913     /// ```
914     /// #![feature(float_minimum_maximum)]
915     /// let x = 1.0f32;
916     /// let y = 2.0f32;
917     ///
918     /// assert_eq!(x.minimum(y), x);
919     /// assert!(x.minimum(f32::NAN).is_nan());
920     /// ```
921     ///
922     /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
923     /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
924     /// Note that this follows the semantics specified in IEEE 754-2019.
925     ///
926     /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
927     /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
928     #[must_use = "this returns the result of the comparison, without modifying either input"]
929     #[unstable(feature = "float_minimum_maximum", issue = "91079")]
930     #[inline]
931     pub fn minimum(self, other: f32) -> f32 {
932         if self < other {
933             self
934         } else if other < self {
935             other
936         } else if self == other {
937             if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
938         } else {
939             self + other
940         }
941     }
942
943     /// Rounds toward zero and converts to any primitive integer type,
944     /// assuming that the value is finite and fits in that type.
945     ///
946     /// ```
947     /// let value = 4.6_f32;
948     /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
949     /// assert_eq!(rounded, 4);
950     ///
951     /// let value = -128.9_f32;
952     /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
953     /// assert_eq!(rounded, i8::MIN);
954     /// ```
955     ///
956     /// # Safety
957     ///
958     /// The value must:
959     ///
960     /// * Not be `NaN`
961     /// * Not be infinite
962     /// * Be representable in the return type `Int`, after truncating off its fractional part
963     #[must_use = "this returns the result of the operation, \
964                   without modifying the original"]
965     #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
966     #[inline]
967     pub unsafe fn to_int_unchecked<Int>(self) -> Int
968     where
969         Self: FloatToInt<Int>,
970     {
971         // SAFETY: the caller must uphold the safety contract for
972         // `FloatToInt::to_int_unchecked`.
973         unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
974     }
975
976     /// Raw transmutation to `u32`.
977     ///
978     /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
979     ///
980     /// See [`from_bits`](Self::from_bits) for some discussion of the
981     /// portability of this operation (there are almost no issues).
982     ///
983     /// Note that this function is distinct from `as` casting, which attempts to
984     /// preserve the *numeric* value, and not the bitwise value.
985     ///
986     /// # Examples
987     ///
988     /// ```
989     /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
990     /// assert_eq!((12.5f32).to_bits(), 0x41480000);
991     ///
992     /// ```
993     #[must_use = "this returns the result of the operation, \
994                   without modifying the original"]
995     #[stable(feature = "float_bits_conv", since = "1.20.0")]
996     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
997     #[inline]
998     pub const fn to_bits(self) -> u32 {
999         // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
1000         // ...sorta.
1001         //
1002         // It turns out that at runtime, it is possible for a floating point number
1003         // to be subject to a floating point mode that alters nonzero subnormal numbers
1004         // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
1005         // This is not a problem per se, but at least one tier2 platform for Rust
1006         // actually exhibits this behavior by default.
1007         //
1008         // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
1009         // i.e. not soft-float, the way Rust does parameter passing can actually alter
1010         // a number that is "not infinity" to have the same exponent as infinity,
1011         // in a slightly unpredictable manner.
1012         //
1013         // And, of course evaluating to a NaN value is fairly nondeterministic.
1014         // More precisely: when NaN should be returned is knowable, but which NaN?
1015         // So far that's defined by a combination of LLVM and the CPU, not Rust.
1016         // This function, however, allows observing the bitstring of a NaN,
1017         // thus introspection on CTFE.
1018         //
1019         // In order to preserve, at least for the moment, const-to-runtime equivalence,
1020         // we reject any of these possible situations from happening.
1021         #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1022         const fn ct_f32_to_u32(ct: f32) -> u32 {
1023             match ct.classify() {
1024                 FpCategory::Nan => {
1025                     panic!("const-eval error: cannot use f32::to_bits on a NaN")
1026                 }
1027                 FpCategory::Subnormal => {
1028                     panic!("const-eval error: cannot use f32::to_bits on a subnormal number")
1029                 }
1030                 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1031                     // SAFETY: We have a normal floating point number. Now we transmute, i.e. do a bitcopy.
1032                     unsafe { mem::transmute::<f32, u32>(ct) }
1033                 }
1034             }
1035         }
1036
1037         #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1038         fn rt_f32_to_u32(x: f32) -> u32 {
1039             // SAFETY: `u32` is a plain old datatype so we can always... uh...
1040             // ...look, just pretend you forgot what you just read.
1041             // Stability concerns.
1042             unsafe { mem::transmute(x) }
1043         }
1044         // SAFETY: We use internal implementations that either always work or fail at compile time.
1045         unsafe { intrinsics::const_eval_select((self,), ct_f32_to_u32, rt_f32_to_u32) }
1046     }
1047
1048     /// Raw transmutation from `u32`.
1049     ///
1050     /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
1051     /// It turns out this is incredibly portable, for two reasons:
1052     ///
1053     /// * Floats and Ints have the same endianness on all supported platforms.
1054     /// * IEEE 754 very precisely specifies the bit layout of floats.
1055     ///
1056     /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1057     /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1058     /// (notably x86 and ARM) picked the interpretation that was ultimately
1059     /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1060     /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1061     ///
1062     /// Rather than trying to preserve signaling-ness cross-platform, this
1063     /// implementation favors preserving the exact bits. This means that
1064     /// any payloads encoded in NaNs will be preserved even if the result of
1065     /// this method is sent over the network from an x86 machine to a MIPS one.
1066     ///
1067     /// If the results of this method are only manipulated by the same
1068     /// architecture that produced them, then there is no portability concern.
1069     ///
1070     /// If the input isn't NaN, then there is no portability concern.
1071     ///
1072     /// If you don't care about signalingness (very likely), then there is no
1073     /// portability concern.
1074     ///
1075     /// Note that this function is distinct from `as` casting, which attempts to
1076     /// preserve the *numeric* value, and not the bitwise value.
1077     ///
1078     /// # Examples
1079     ///
1080     /// ```
1081     /// let v = f32::from_bits(0x41480000);
1082     /// assert_eq!(v, 12.5);
1083     /// ```
1084     #[stable(feature = "float_bits_conv", since = "1.20.0")]
1085     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1086     #[must_use]
1087     #[inline]
1088     pub const fn from_bits(v: u32) -> Self {
1089         // It turns out the safety issues with sNaN were overblown! Hooray!
1090         // SAFETY: `u32` is a plain old datatype so we can always transmute from it
1091         // ...sorta.
1092         //
1093         // It turns out that at runtime, it is possible for a floating point number
1094         // to be subject to floating point modes that alter nonzero subnormal numbers
1095         // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
1096         // This is not a problem usually, but at least one tier2 platform for Rust
1097         // actually exhibits this behavior by default: thumbv7neon
1098         // aka "the Neon FPU in AArch32 state"
1099         //
1100         // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
1101         // i.e. not soft-float, the way Rust does parameter passing can actually alter
1102         // a number that is "not infinity" to have the same exponent as infinity,
1103         // in a slightly unpredictable manner.
1104         //
1105         // And, of course evaluating to a NaN value is fairly nondeterministic.
1106         // More precisely: when NaN should be returned is knowable, but which NaN?
1107         // So far that's defined by a combination of LLVM and the CPU, not Rust.
1108         // This function, however, allows observing the bitstring of a NaN,
1109         // thus introspection on CTFE.
1110         //
1111         // In order to preserve, at least for the moment, const-to-runtime equivalence,
1112         // reject any of these possible situations from happening.
1113         #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1114         const fn ct_u32_to_f32(ct: u32) -> f32 {
1115             match f32::classify_bits(ct) {
1116                 FpCategory::Subnormal => {
1117                     panic!("const-eval error: cannot use f32::from_bits on a subnormal number")
1118                 }
1119                 FpCategory::Nan => {
1120                     panic!("const-eval error: cannot use f32::from_bits on NaN")
1121                 }
1122                 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1123                     // SAFETY: It's not a frumious number
1124                     unsafe { mem::transmute::<u32, f32>(ct) }
1125                 }
1126             }
1127         }
1128
1129         #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1130         fn rt_u32_to_f32(x: u32) -> f32 {
1131             // SAFETY: `u32` is a plain old datatype so we can always... uh...
1132             // ...look, just pretend you forgot what you just read.
1133             // Stability concerns.
1134             unsafe { mem::transmute(x) }
1135         }
1136         // SAFETY: We use internal implementations that either always work or fail at compile time.
1137         unsafe { intrinsics::const_eval_select((v,), ct_u32_to_f32, rt_u32_to_f32) }
1138     }
1139
1140     /// Return the memory representation of this floating point number as a byte array in
1141     /// big-endian (network) byte order.
1142     ///
1143     /// See [`from_bits`](Self::from_bits) for some discussion of the
1144     /// portability of this operation (there are almost no issues).
1145     ///
1146     /// # Examples
1147     ///
1148     /// ```
1149     /// let bytes = 12.5f32.to_be_bytes();
1150     /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1151     /// ```
1152     #[must_use = "this returns the result of the operation, \
1153                   without modifying the original"]
1154     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1155     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1156     #[inline]
1157     pub const fn to_be_bytes(self) -> [u8; 4] {
1158         self.to_bits().to_be_bytes()
1159     }
1160
1161     /// Return the memory representation of this floating point number as a byte array in
1162     /// little-endian byte order.
1163     ///
1164     /// See [`from_bits`](Self::from_bits) for some discussion of the
1165     /// portability of this operation (there are almost no issues).
1166     ///
1167     /// # Examples
1168     ///
1169     /// ```
1170     /// let bytes = 12.5f32.to_le_bytes();
1171     /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1172     /// ```
1173     #[must_use = "this returns the result of the operation, \
1174                   without modifying the original"]
1175     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1176     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1177     #[inline]
1178     pub const fn to_le_bytes(self) -> [u8; 4] {
1179         self.to_bits().to_le_bytes()
1180     }
1181
1182     /// Return the memory representation of this floating point number as a byte array in
1183     /// native byte order.
1184     ///
1185     /// As the target platform's native endianness is used, portable code
1186     /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1187     ///
1188     /// [`to_be_bytes`]: f32::to_be_bytes
1189     /// [`to_le_bytes`]: f32::to_le_bytes
1190     ///
1191     /// See [`from_bits`](Self::from_bits) for some discussion of the
1192     /// portability of this operation (there are almost no issues).
1193     ///
1194     /// # Examples
1195     ///
1196     /// ```
1197     /// let bytes = 12.5f32.to_ne_bytes();
1198     /// assert_eq!(
1199     ///     bytes,
1200     ///     if cfg!(target_endian = "big") {
1201     ///         [0x41, 0x48, 0x00, 0x00]
1202     ///     } else {
1203     ///         [0x00, 0x00, 0x48, 0x41]
1204     ///     }
1205     /// );
1206     /// ```
1207     #[must_use = "this returns the result of the operation, \
1208                   without modifying the original"]
1209     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1210     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1211     #[inline]
1212     pub const fn to_ne_bytes(self) -> [u8; 4] {
1213         self.to_bits().to_ne_bytes()
1214     }
1215
1216     /// Create a floating point value from its representation as a byte array in big endian.
1217     ///
1218     /// See [`from_bits`](Self::from_bits) for some discussion of the
1219     /// portability of this operation (there are almost no issues).
1220     ///
1221     /// # Examples
1222     ///
1223     /// ```
1224     /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1225     /// assert_eq!(value, 12.5);
1226     /// ```
1227     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1228     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1229     #[must_use]
1230     #[inline]
1231     pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1232         Self::from_bits(u32::from_be_bytes(bytes))
1233     }
1234
1235     /// Create a floating point value from its representation as a byte array in little endian.
1236     ///
1237     /// See [`from_bits`](Self::from_bits) for some discussion of the
1238     /// portability of this operation (there are almost no issues).
1239     ///
1240     /// # Examples
1241     ///
1242     /// ```
1243     /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1244     /// assert_eq!(value, 12.5);
1245     /// ```
1246     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1247     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1248     #[must_use]
1249     #[inline]
1250     pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1251         Self::from_bits(u32::from_le_bytes(bytes))
1252     }
1253
1254     /// Create a floating point value from its representation as a byte array in native endian.
1255     ///
1256     /// As the target platform's native endianness is used, portable code
1257     /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1258     /// appropriate instead.
1259     ///
1260     /// [`from_be_bytes`]: f32::from_be_bytes
1261     /// [`from_le_bytes`]: f32::from_le_bytes
1262     ///
1263     /// See [`from_bits`](Self::from_bits) for some discussion of the
1264     /// portability of this operation (there are almost no issues).
1265     ///
1266     /// # Examples
1267     ///
1268     /// ```
1269     /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1270     ///     [0x41, 0x48, 0x00, 0x00]
1271     /// } else {
1272     ///     [0x00, 0x00, 0x48, 0x41]
1273     /// });
1274     /// assert_eq!(value, 12.5);
1275     /// ```
1276     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1277     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1278     #[must_use]
1279     #[inline]
1280     pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1281         Self::from_bits(u32::from_ne_bytes(bytes))
1282     }
1283
1284     /// Return the ordering between `self` and `other`.
1285     ///
1286     /// Unlike the standard partial comparison between floating point numbers,
1287     /// this comparison always produces an ordering in accordance to
1288     /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1289     /// floating point standard. The values are ordered in the following sequence:
1290     ///
1291     /// - negative quiet NaN
1292     /// - negative signaling NaN
1293     /// - negative infinity
1294     /// - negative numbers
1295     /// - negative subnormal numbers
1296     /// - negative zero
1297     /// - positive zero
1298     /// - positive subnormal numbers
1299     /// - positive numbers
1300     /// - positive infinity
1301     /// - positive signaling NaN
1302     /// - positive quiet NaN.
1303     ///
1304     /// The ordering established by this function does not always agree with the
1305     /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1306     /// they consider negative and positive zero equal, while `total_cmp`
1307     /// doesn't.
1308     ///
1309     /// The interpretation of the signaling NaN bit follows the definition in
1310     /// the IEEE 754 standard, which may not match the interpretation by some of
1311     /// the older, non-conformant (e.g. MIPS) hardware implementations.
1312     ///
1313     /// # Example
1314     ///
1315     /// ```
1316     /// struct GoodBoy {
1317     ///     name: String,
1318     ///     weight: f32,
1319     /// }
1320     ///
1321     /// let mut bois = vec![
1322     ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1323     ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1324     ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1325     ///     GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1326     ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1327     ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1328     /// ];
1329     ///
1330     /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1331     /// # assert!(bois.into_iter().map(|b| b.weight)
1332     /// #     .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1333     /// #     .all(|(a, b)| a.to_bits() == b.to_bits()))
1334     /// ```
1335     #[stable(feature = "total_cmp", since = "1.62.0")]
1336     #[must_use]
1337     #[inline]
1338     pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1339         let mut left = self.to_bits() as i32;
1340         let mut right = other.to_bits() as i32;
1341
1342         // In case of negatives, flip all the bits except the sign
1343         // to achieve a similar layout as two's complement integers
1344         //
1345         // Why does this work? IEEE 754 floats consist of three fields:
1346         // Sign bit, exponent and mantissa. The set of exponent and mantissa
1347         // fields as a whole have the property that their bitwise order is
1348         // equal to the numeric magnitude where the magnitude is defined.
1349         // The magnitude is not normally defined on NaN values, but
1350         // IEEE 754 totalOrder defines the NaN values also to follow the
1351         // bitwise order. This leads to order explained in the doc comment.
1352         // However, the representation of magnitude is the same for negative
1353         // and positive numbers – only the sign bit is different.
1354         // To easily compare the floats as signed integers, we need to
1355         // flip the exponent and mantissa bits in case of negative numbers.
1356         // We effectively convert the numbers to "two's complement" form.
1357         //
1358         // To do the flipping, we construct a mask and XOR against it.
1359         // We branchlessly calculate an "all-ones except for the sign bit"
1360         // mask from negative-signed values: right shifting sign-extends
1361         // the integer, so we "fill" the mask with sign bits, and then
1362         // convert to unsigned to push one more zero bit.
1363         // On positive values, the mask is all zeros, so it's a no-op.
1364         left ^= (((left >> 31) as u32) >> 1) as i32;
1365         right ^= (((right >> 31) as u32) >> 1) as i32;
1366
1367         left.cmp(&right)
1368     }
1369
1370     /// Restrict a value to a certain interval unless it is NaN.
1371     ///
1372     /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1373     /// less than `min`. Otherwise this returns `self`.
1374     ///
1375     /// Note that this function returns NaN if the initial value was NaN as
1376     /// well.
1377     ///
1378     /// # Panics
1379     ///
1380     /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1381     ///
1382     /// # Examples
1383     ///
1384     /// ```
1385     /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1386     /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1387     /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1388     /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1389     /// ```
1390     #[must_use = "method returns a new number and does not mutate the original value"]
1391     #[stable(feature = "clamp", since = "1.50.0")]
1392     #[inline]
1393     pub fn clamp(mut self, min: f32, max: f32) -> f32 {
1394         assert!(min <= max);
1395         if self < min {
1396             self = min;
1397         }
1398         if self > max {
1399             self = max;
1400         }
1401         self
1402     }
1403 }