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