Debian Codegraph @

debian/rust-vendor/jiff/src/util/libm.rs

raw
1 /*!
2 A no-std module for some floating point operations.
3
4 These were vendored from the [`libm`] crate. For no-std specifically, I
5 wouldn't necessarily mind depending on `libm`, but I don't think there's a
6 way to express "only depend on a crate if some on-by-default feature is not
7 enabled."
8
9 We also very intentionally have very minimal floating point requirements. It's
10 used for `Span::total` where it's part of the API and thus necessary. It's also
11 used in floating point conversion routings to `jiff::SignedDuration`.
12
13 [`libm`]: https://github.com/rust-lang/libm
14 */
15
16 pub(crate) trait Float {
17 fn round(self) -> Self;
18 fn trunc(self) -> Self;
19 fn fract(self) -> Self;
20 }
21
22 const TOINT64: f64 = 1. / f64::EPSILON;
23
24 impl Float for f64 {
25 fn round(self) -> f64 {
26 (self + copysign64(0.5 - 0.25 * f64::EPSILON, self)).trunc()
27 }
28
29 fn trunc(self) -> f64 {
30 let x = self;
31 let x1p120 = f64::from_bits(0x4770000000000000); // 0x1p120f === 2 ^ 120
32
33 let mut i: u64 = x.to_bits();
34 let mut e: i64 = (i >> 52 & 0x7ff) as i64 - 0x3ff + 12;
35 let m: u64;
36
37 if e >= 52 + 12 {
38 return x;
39 }
40 if e < 12 {
41 e = 1;
42 }
43 m = -1i64 as u64 >> e;
44 if (i & m) == 0 {
45 return x;
46 }
47 core::hint::black_box(x + x1p120);
48 i &= !m;
49 f64::from_bits(i)
50 }
51
52 fn fract(self) -> f64 {
53 self - self.trunc()
54 }
55 }
56
57 impl Float for f32 {
58 fn round(self) -> f32 {
59 (self + copysign32(0.5 - 0.25 * f32::EPSILON, self)).trunc()
60 }
61
62 fn trunc(self) -> f32 {
63 let x = self;
64 let x1p120 = f32::from_bits(0x7b800000); // 0x1p120f === 2 ^ 120
65
66 let mut i: u32 = x.to_bits();
67 let mut e: i32 = (i >> 23 & 0xff) as i32 - 0x7f + 9;
68 let m: u32;
69
70 if e >= 23 + 9 {
71 return x;
72 }
73 if e < 9 {
74 e = 1;
75 }
76 m = -1i32 as u32 >> e;
77 if (i & m) == 0 {
78 return x;
79 }
80 core::hint::black_box(x + x1p120);
81 i &= !m;
82 f32::from_bits(i)
83 }
84
85 fn fract(self) -> f32 {
86 self - self.trunc()
87 }
88 }
89
90 fn copysign64(x: f64, y: f64) -> f64 {
91 let mut ux = x.to_bits();
92 let uy = y.to_bits();
93 ux &= (!0) >> 1;
94 ux |= uy & (1 << 63);
95 f64::from_bits(ux)
96 }
97
98 fn copysign32(x: f32, y: f32) -> f32 {
99 let mut ux = x.to_bits();
100 let uy = y.to_bits();
101 ux &= 0x7fffffff;
102 ux |= uy & 0x80000000;
103 f32::from_bits(ux)
104 }