]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/f32.rs
Rectify float classification impls for weird FPUs
[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     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
613     const unsafe fn partial_classify(self) -> FpCategory {
614         const EXP_MASK: u32 = 0x7f800000;
615         const MAN_MASK: u32 = 0x007fffff;
616
617         // SAFETY: The caller is not asking questions for which this will tell lies.
618         let b = unsafe { mem::transmute::<f32, u32>(self) };
619         match (b & MAN_MASK, b & EXP_MASK) {
620             (0, 0) => FpCategory::Zero,
621             (_, 0) => FpCategory::Subnormal,
622             _ => FpCategory::Normal,
623         }
624     }
625
626     /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
627     /// positive sign bit and positive infinity.
628     ///
629     /// ```
630     /// let f = 7.0_f32;
631     /// let g = -7.0_f32;
632     ///
633     /// assert!(f.is_sign_positive());
634     /// assert!(!g.is_sign_positive());
635     /// ```
636     #[must_use]
637     #[stable(feature = "rust1", since = "1.0.0")]
638     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
639     #[inline]
640     pub const fn is_sign_positive(self) -> bool {
641         !self.is_sign_negative()
642     }
643
644     /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
645     /// negative sign bit and negative infinity.
646     ///
647     /// ```
648     /// let f = 7.0f32;
649     /// let g = -7.0f32;
650     ///
651     /// assert!(!f.is_sign_negative());
652     /// assert!(g.is_sign_negative());
653     /// ```
654     #[must_use]
655     #[stable(feature = "rust1", since = "1.0.0")]
656     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
657     #[inline]
658     pub const fn is_sign_negative(self) -> bool {
659         // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
660         // applies to zeros and NaNs as well.
661         // SAFETY: This is just transmuting to get the sign bit, it's fine.
662         unsafe { mem::transmute::<f32, u32>(self) & 0x8000_0000 != 0 }
663     }
664
665     /// Takes the reciprocal (inverse) of a number, `1/x`.
666     ///
667     /// ```
668     /// let x = 2.0_f32;
669     /// let abs_difference = (x.recip() - (1.0 / x)).abs();
670     ///
671     /// assert!(abs_difference <= f32::EPSILON);
672     /// ```
673     #[must_use = "this returns the result of the operation, without modifying the original"]
674     #[stable(feature = "rust1", since = "1.0.0")]
675     #[inline]
676     pub fn recip(self) -> f32 {
677         1.0 / self
678     }
679
680     /// Converts radians to degrees.
681     ///
682     /// ```
683     /// let angle = std::f32::consts::PI;
684     ///
685     /// let abs_difference = (angle.to_degrees() - 180.0).abs();
686     ///
687     /// assert!(abs_difference <= f32::EPSILON);
688     /// ```
689     #[must_use = "this returns the result of the operation, \
690                   without modifying the original"]
691     #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
692     #[inline]
693     pub fn to_degrees(self) -> f32 {
694         // Use a constant for better precision.
695         const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
696         self * PIS_IN_180
697     }
698
699     /// Converts degrees to radians.
700     ///
701     /// ```
702     /// let angle = 180.0f32;
703     ///
704     /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
705     ///
706     /// assert!(abs_difference <= f32::EPSILON);
707     /// ```
708     #[must_use = "this returns the result of the operation, \
709                   without modifying the original"]
710     #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
711     #[inline]
712     pub fn to_radians(self) -> f32 {
713         let value: f32 = consts::PI;
714         self * (value / 180.0f32)
715     }
716
717     /// Returns the maximum of the two numbers.
718     ///
719     /// Follows the IEEE-754 2008 semantics for maxNum, except for handling of signaling NaNs.
720     /// This matches the behavior of libm’s fmax.
721     ///
722     /// ```
723     /// let x = 1.0f32;
724     /// let y = 2.0f32;
725     ///
726     /// assert_eq!(x.max(y), y);
727     /// ```
728     ///
729     /// If one of the arguments is NaN, then the other argument is returned.
730     #[must_use = "this returns the result of the comparison, without modifying either input"]
731     #[stable(feature = "rust1", since = "1.0.0")]
732     #[inline]
733     pub fn max(self, other: f32) -> f32 {
734         intrinsics::maxnumf32(self, other)
735     }
736
737     /// Returns the minimum of the two numbers.
738     ///
739     /// Follows the IEEE-754 2008 semantics for minNum, except for handling of signaling NaNs.
740     /// This matches the behavior of libm’s fmin.
741     ///
742     /// ```
743     /// let x = 1.0f32;
744     /// let y = 2.0f32;
745     ///
746     /// assert_eq!(x.min(y), x);
747     /// ```
748     ///
749     /// If one of the arguments is NaN, then the other argument is returned.
750     #[must_use = "this returns the result of the comparison, without modifying either input"]
751     #[stable(feature = "rust1", since = "1.0.0")]
752     #[inline]
753     pub fn min(self, other: f32) -> f32 {
754         intrinsics::minnumf32(self, other)
755     }
756
757     /// Returns the maximum of the two numbers, propagating NaNs.
758     ///
759     /// This returns NaN when *either* argument is NaN, as opposed to
760     /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
761     ///
762     /// ```
763     /// #![feature(float_minimum_maximum)]
764     /// let x = 1.0f32;
765     /// let y = 2.0f32;
766     ///
767     /// assert_eq!(x.maximum(y), y);
768     /// assert!(x.maximum(f32::NAN).is_nan());
769     /// ```
770     ///
771     /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
772     /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
773     /// Note that this follows the semantics specified in IEEE 754-2019.
774     #[must_use = "this returns the result of the comparison, without modifying either input"]
775     #[unstable(feature = "float_minimum_maximum", issue = "91079")]
776     #[inline]
777     pub fn maximum(self, other: f32) -> f32 {
778         if self > other {
779             self
780         } else if other > self {
781             other
782         } else if self == other {
783             if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
784         } else {
785             self + other
786         }
787     }
788
789     /// Returns the minimum of the two numbers, propagating NaNs.
790     ///
791     /// This returns NaN when *either* argument is NaN, as opposed to
792     /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
793     ///
794     /// ```
795     /// #![feature(float_minimum_maximum)]
796     /// let x = 1.0f32;
797     /// let y = 2.0f32;
798     ///
799     /// assert_eq!(x.minimum(y), x);
800     /// assert!(x.minimum(f32::NAN).is_nan());
801     /// ```
802     ///
803     /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
804     /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
805     /// Note that this follows the semantics specified in IEEE 754-2019.
806     #[must_use = "this returns the result of the comparison, without modifying either input"]
807     #[unstable(feature = "float_minimum_maximum", issue = "91079")]
808     #[inline]
809     pub fn minimum(self, other: f32) -> f32 {
810         if self < other {
811             self
812         } else if other < self {
813             other
814         } else if self == other {
815             if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
816         } else {
817             self + other
818         }
819     }
820
821     /// Rounds toward zero and converts to any primitive integer type,
822     /// assuming that the value is finite and fits in that type.
823     ///
824     /// ```
825     /// let value = 4.6_f32;
826     /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
827     /// assert_eq!(rounded, 4);
828     ///
829     /// let value = -128.9_f32;
830     /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
831     /// assert_eq!(rounded, i8::MIN);
832     /// ```
833     ///
834     /// # Safety
835     ///
836     /// The value must:
837     ///
838     /// * Not be `NaN`
839     /// * Not be infinite
840     /// * Be representable in the return type `Int`, after truncating off its fractional part
841     #[must_use = "this returns the result of the operation, \
842                   without modifying the original"]
843     #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
844     #[inline]
845     pub unsafe fn to_int_unchecked<Int>(self) -> Int
846     where
847         Self: FloatToInt<Int>,
848     {
849         // SAFETY: the caller must uphold the safety contract for
850         // `FloatToInt::to_int_unchecked`.
851         unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
852     }
853
854     /// Raw transmutation to `u32`.
855     ///
856     /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
857     ///
858     /// See [`from_bits`](Self::from_bits) for some discussion of the
859     /// portability of this operation (there are almost no issues).
860     ///
861     /// Note that this function is distinct from `as` casting, which attempts to
862     /// preserve the *numeric* value, and not the bitwise value.
863     ///
864     /// # Examples
865     ///
866     /// ```
867     /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
868     /// assert_eq!((12.5f32).to_bits(), 0x41480000);
869     ///
870     /// ```
871     #[must_use = "this returns the result of the operation, \
872                   without modifying the original"]
873     #[stable(feature = "float_bits_conv", since = "1.20.0")]
874     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
875     #[inline]
876     pub const fn to_bits(self) -> u32 {
877         // SAFETY: `u32` is a plain old datatype so we can always transmute to it
878         unsafe { mem::transmute(self) }
879     }
880
881     /// Raw transmutation from `u32`.
882     ///
883     /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
884     /// It turns out this is incredibly portable, for two reasons:
885     ///
886     /// * Floats and Ints have the same endianness on all supported platforms.
887     /// * IEEE-754 very precisely specifies the bit layout of floats.
888     ///
889     /// However there is one caveat: prior to the 2008 version of IEEE-754, how
890     /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
891     /// (notably x86 and ARM) picked the interpretation that was ultimately
892     /// standardized in 2008, but some didn't (notably MIPS). As a result, all
893     /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
894     ///
895     /// Rather than trying to preserve signaling-ness cross-platform, this
896     /// implementation favors preserving the exact bits. This means that
897     /// any payloads encoded in NaNs will be preserved even if the result of
898     /// this method is sent over the network from an x86 machine to a MIPS one.
899     ///
900     /// If the results of this method are only manipulated by the same
901     /// architecture that produced them, then there is no portability concern.
902     ///
903     /// If the input isn't NaN, then there is no portability concern.
904     ///
905     /// If you don't care about signalingness (very likely), then there is no
906     /// portability concern.
907     ///
908     /// Note that this function is distinct from `as` casting, which attempts to
909     /// preserve the *numeric* value, and not the bitwise value.
910     ///
911     /// # Examples
912     ///
913     /// ```
914     /// let v = f32::from_bits(0x41480000);
915     /// assert_eq!(v, 12.5);
916     /// ```
917     #[stable(feature = "float_bits_conv", since = "1.20.0")]
918     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
919     #[must_use]
920     #[inline]
921     pub const fn from_bits(v: u32) -> Self {
922         // SAFETY: `u32` is a plain old datatype so we can always transmute from it
923         // It turns out the safety issues with sNaN were overblown! Hooray!
924         unsafe { mem::transmute::<u32, f32>(v) }
925     }
926
927     /// Return the memory representation of this floating point number as a byte array in
928     /// big-endian (network) byte order.
929     ///
930     /// # Examples
931     ///
932     /// ```
933     /// let bytes = 12.5f32.to_be_bytes();
934     /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
935     /// ```
936     #[must_use = "this returns the result of the operation, \
937                   without modifying the original"]
938     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
939     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
940     #[inline]
941     pub const fn to_be_bytes(self) -> [u8; 4] {
942         self.to_bits().to_be_bytes()
943     }
944
945     /// Return the memory representation of this floating point number as a byte array in
946     /// little-endian byte order.
947     ///
948     /// # Examples
949     ///
950     /// ```
951     /// let bytes = 12.5f32.to_le_bytes();
952     /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
953     /// ```
954     #[must_use = "this returns the result of the operation, \
955                   without modifying the original"]
956     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
957     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
958     #[inline]
959     pub const fn to_le_bytes(self) -> [u8; 4] {
960         self.to_bits().to_le_bytes()
961     }
962
963     /// Return the memory representation of this floating point number as a byte array in
964     /// native byte order.
965     ///
966     /// As the target platform's native endianness is used, portable code
967     /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
968     ///
969     /// [`to_be_bytes`]: f32::to_be_bytes
970     /// [`to_le_bytes`]: f32::to_le_bytes
971     ///
972     /// # Examples
973     ///
974     /// ```
975     /// let bytes = 12.5f32.to_ne_bytes();
976     /// assert_eq!(
977     ///     bytes,
978     ///     if cfg!(target_endian = "big") {
979     ///         [0x41, 0x48, 0x00, 0x00]
980     ///     } else {
981     ///         [0x00, 0x00, 0x48, 0x41]
982     ///     }
983     /// );
984     /// ```
985     #[must_use = "this returns the result of the operation, \
986                   without modifying the original"]
987     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
988     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
989     #[inline]
990     pub const fn to_ne_bytes(self) -> [u8; 4] {
991         self.to_bits().to_ne_bytes()
992     }
993
994     /// Create a floating point value from its representation as a byte array in big endian.
995     ///
996     /// # Examples
997     ///
998     /// ```
999     /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1000     /// assert_eq!(value, 12.5);
1001     /// ```
1002     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1003     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1004     #[must_use]
1005     #[inline]
1006     pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1007         Self::from_bits(u32::from_be_bytes(bytes))
1008     }
1009
1010     /// Create a floating point value from its representation as a byte array in little endian.
1011     ///
1012     /// # Examples
1013     ///
1014     /// ```
1015     /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1016     /// assert_eq!(value, 12.5);
1017     /// ```
1018     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1019     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1020     #[must_use]
1021     #[inline]
1022     pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1023         Self::from_bits(u32::from_le_bytes(bytes))
1024     }
1025
1026     /// Create a floating point value from its representation as a byte array in native endian.
1027     ///
1028     /// As the target platform's native endianness is used, portable code
1029     /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1030     /// appropriate instead.
1031     ///
1032     /// [`from_be_bytes`]: f32::from_be_bytes
1033     /// [`from_le_bytes`]: f32::from_le_bytes
1034     ///
1035     /// # Examples
1036     ///
1037     /// ```
1038     /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1039     ///     [0x41, 0x48, 0x00, 0x00]
1040     /// } else {
1041     ///     [0x00, 0x00, 0x48, 0x41]
1042     /// });
1043     /// assert_eq!(value, 12.5);
1044     /// ```
1045     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1046     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1047     #[must_use]
1048     #[inline]
1049     pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1050         Self::from_bits(u32::from_ne_bytes(bytes))
1051     }
1052
1053     /// Return the ordering between `self` and `other`.
1054     ///
1055     /// Unlike the standard partial comparison between floating point numbers,
1056     /// this comparison always produces an ordering in accordance to
1057     /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1058     /// floating point standard. The values are ordered in the following sequence:
1059     ///
1060     /// - negative quiet NaN
1061     /// - negative signaling NaN
1062     /// - negative infinity
1063     /// - negative numbers
1064     /// - negative subnormal numbers
1065     /// - negative zero
1066     /// - positive zero
1067     /// - positive subnormal numbers
1068     /// - positive numbers
1069     /// - positive infinity
1070     /// - positive signaling NaN
1071     /// - positive quiet NaN.
1072     ///
1073     /// The ordering established by this function does not always agree with the
1074     /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1075     /// they consider negative and positive zero equal, while `total_cmp`
1076     /// doesn't.
1077     ///
1078     /// The interpretation of the signaling NaN bit follows the definition in
1079     /// the IEEE 754 standard, which may not match the interpretation by some of
1080     /// the older, non-conformant (e.g. MIPS) hardware implementations.
1081     ///
1082     /// # Example
1083     ///
1084     /// ```
1085     /// struct GoodBoy {
1086     ///     name: String,
1087     ///     weight: f32,
1088     /// }
1089     ///
1090     /// let mut bois = vec![
1091     ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1092     ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1093     ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1094     ///     GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1095     ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1096     ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1097     /// ];
1098     ///
1099     /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1100     /// # assert!(bois.into_iter().map(|b| b.weight)
1101     /// #     .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1102     /// #     .all(|(a, b)| a.to_bits() == b.to_bits()))
1103     /// ```
1104     #[stable(feature = "total_cmp", since = "1.62.0")]
1105     #[must_use]
1106     #[inline]
1107     pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1108         let mut left = self.to_bits() as i32;
1109         let mut right = other.to_bits() as i32;
1110
1111         // In case of negatives, flip all the bits except the sign
1112         // to achieve a similar layout as two's complement integers
1113         //
1114         // Why does this work? IEEE 754 floats consist of three fields:
1115         // Sign bit, exponent and mantissa. The set of exponent and mantissa
1116         // fields as a whole have the property that their bitwise order is
1117         // equal to the numeric magnitude where the magnitude is defined.
1118         // The magnitude is not normally defined on NaN values, but
1119         // IEEE 754 totalOrder defines the NaN values also to follow the
1120         // bitwise order. This leads to order explained in the doc comment.
1121         // However, the representation of magnitude is the same for negative
1122         // and positive numbers – only the sign bit is different.
1123         // To easily compare the floats as signed integers, we need to
1124         // flip the exponent and mantissa bits in case of negative numbers.
1125         // We effectively convert the numbers to "two's complement" form.
1126         //
1127         // To do the flipping, we construct a mask and XOR against it.
1128         // We branchlessly calculate an "all-ones except for the sign bit"
1129         // mask from negative-signed values: right shifting sign-extends
1130         // the integer, so we "fill" the mask with sign bits, and then
1131         // convert to unsigned to push one more zero bit.
1132         // On positive values, the mask is all zeros, so it's a no-op.
1133         left ^= (((left >> 31) as u32) >> 1) as i32;
1134         right ^= (((right >> 31) as u32) >> 1) as i32;
1135
1136         left.cmp(&right)
1137     }
1138
1139     /// Restrict a value to a certain interval unless it is NaN.
1140     ///
1141     /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1142     /// less than `min`. Otherwise this returns `self`.
1143     ///
1144     /// Note that this function returns NaN if the initial value was NaN as
1145     /// well.
1146     ///
1147     /// # Panics
1148     ///
1149     /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1150     ///
1151     /// # Examples
1152     ///
1153     /// ```
1154     /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1155     /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1156     /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1157     /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1158     /// ```
1159     #[must_use = "method returns a new number and does not mutate the original value"]
1160     #[stable(feature = "clamp", since = "1.50.0")]
1161     #[inline]
1162     pub fn clamp(self, min: f32, max: f32) -> f32 {
1163         assert!(min <= max);
1164         let mut x = self;
1165         if x < min {
1166             x = min;
1167         }
1168         if x > max {
1169             x = max;
1170         }
1171         x
1172     }
1173 }