datafusion_common/
rounding.rs1use std::ops::{Add, BitAnd, Sub};
11
12use crate::Result;
13use crate::ScalarValue;
14
15#[cfg(all(target_arch = "aarch64", not(target_os = "windows")))]
17const FE_UPWARD: i32 = 0x00400000;
18#[cfg(all(target_arch = "aarch64", not(target_os = "windows")))]
19const FE_DOWNWARD: i32 = 0x00800000;
20
21#[cfg(all(target_arch = "x86_64", not(target_os = "windows")))]
23const FE_UPWARD: i32 = 0x0800;
24#[cfg(all(target_arch = "x86_64", not(target_os = "windows")))]
25const FE_DOWNWARD: i32 = 0x0400;
26
27#[cfg(all(
28 any(target_arch = "x86_64", target_arch = "aarch64"),
29 not(target_os = "windows")
30))]
31extern crate libc;
32
33#[cfg(all(
34 any(target_arch = "x86_64", target_arch = "aarch64"),
35 not(target_os = "windows")
36))]
37unsafe extern "C" {
38 fn fesetround(round: i32);
39 fn fegetround() -> i32;
40}
41
42pub trait FloatBits {
46 type Item: Copy
48 + PartialEq
49 + BitAnd<Output = Self::Item>
50 + Add<Output = Self::Item>
51 + Sub<Output = Self::Item>;
52
53 const TINY_BITS: Self::Item;
55
56 const NEG_TINY_BITS: Self::Item;
58
59 const CLEAR_SIGN_MASK: Self::Item;
61
62 const ONE: Self::Item;
64
65 const ZERO: Self::Item;
67 const NEG_ZERO: Self::Item;
68
69 fn to_bits(self) -> Self::Item;
71
72 fn from_bits(bits: Self::Item) -> Self;
74
75 fn float_is_nan(self) -> bool;
77
78 fn infinity() -> Self;
80
81 fn neg_infinity() -> Self;
83}
84
85impl FloatBits for f32 {
86 type Item = u32;
87 const TINY_BITS: u32 = 0x1; const NEG_TINY_BITS: u32 = 0x8000_0001; const CLEAR_SIGN_MASK: u32 = 0x7fff_ffff;
90 const ONE: Self::Item = 1;
91 const ZERO: Self::Item = 0;
92 const NEG_ZERO: Self::Item = 0x8000_0000;
93
94 fn to_bits(self) -> Self::Item {
95 self.to_bits()
96 }
97
98 fn from_bits(bits: Self::Item) -> Self {
99 f32::from_bits(bits)
100 }
101
102 fn float_is_nan(self) -> bool {
103 self.is_nan()
104 }
105
106 fn infinity() -> Self {
107 f32::INFINITY
108 }
109
110 fn neg_infinity() -> Self {
111 f32::NEG_INFINITY
112 }
113}
114
115impl FloatBits for f64 {
116 type Item = u64;
117 const TINY_BITS: u64 = 0x1; const NEG_TINY_BITS: u64 = 0x8000_0000_0000_0001; const CLEAR_SIGN_MASK: u64 = 0x7fff_ffff_ffff_ffff;
120 const ONE: Self::Item = 1;
121 const ZERO: Self::Item = 0;
122 const NEG_ZERO: Self::Item = 0x8000_0000_0000_0000;
123
124 fn to_bits(self) -> Self::Item {
125 self.to_bits()
126 }
127
128 fn from_bits(bits: Self::Item) -> Self {
129 f64::from_bits(bits)
130 }
131
132 fn float_is_nan(self) -> bool {
133 self.is_nan()
134 }
135
136 fn infinity() -> Self {
137 f64::INFINITY
138 }
139
140 fn neg_infinity() -> Self {
141 f64::NEG_INFINITY
142 }
143}
144
145pub fn next_up<F: FloatBits + Copy>(float: F) -> F {
162 let bits = float.to_bits();
163 if float.float_is_nan() || bits == F::infinity().to_bits() {
164 return float;
165 }
166
167 let abs = bits & F::CLEAR_SIGN_MASK;
168 let next_bits = if bits == F::ZERO {
169 F::TINY_BITS
170 } else if abs == F::ZERO {
171 F::ZERO
172 } else if bits == abs {
173 bits + F::ONE
174 } else {
175 bits - F::ONE
176 };
177 F::from_bits(next_bits)
178}
179
180pub fn next_down<F: FloatBits + Copy>(float: F) -> F {
197 let bits = float.to_bits();
198 if float.float_is_nan() || bits == F::neg_infinity().to_bits() {
199 return float;
200 }
201
202 let abs = bits & F::CLEAR_SIGN_MASK;
203 let next_bits = if bits == F::ZERO {
204 F::NEG_ZERO
205 } else if abs == F::ZERO {
206 F::NEG_TINY_BITS
207 } else if bits == abs {
208 bits - F::ONE
209 } else {
210 bits + F::ONE
211 };
212 F::from_bits(next_bits)
213}
214
215#[cfg(any(
216 not(any(target_arch = "x86_64", target_arch = "aarch64")),
217 target_os = "windows"
218))]
219fn alter_fp_rounding_mode_conservative<const UPPER: bool, F>(
220 lhs: &ScalarValue,
221 rhs: &ScalarValue,
222 operation: F,
223) -> Result<ScalarValue>
224where
225 F: FnOnce(&ScalarValue, &ScalarValue) -> Result<ScalarValue>,
226{
227 let mut result = operation(lhs, rhs)?;
228 match &mut result {
229 ScalarValue::Float64(Some(value)) => {
230 if UPPER {
231 *value = next_up(*value)
232 } else {
233 *value = next_down(*value)
234 }
235 }
236 ScalarValue::Float32(Some(value)) => {
237 if UPPER {
238 *value = next_up(*value)
239 } else {
240 *value = next_down(*value)
241 }
242 }
243 _ => {}
244 }
245 Ok(result)
246}
247
248pub fn alter_fp_rounding_mode<const UPPER: bool, F>(
249 lhs: &ScalarValue,
250 rhs: &ScalarValue,
251 operation: F,
252) -> Result<ScalarValue>
253where
254 F: FnOnce(&ScalarValue, &ScalarValue) -> Result<ScalarValue>,
255{
256 #[cfg(all(
257 any(target_arch = "x86_64", target_arch = "aarch64"),
258 not(target_os = "windows")
259 ))]
260 unsafe {
261 struct RoundingModeGuard(i32);
262
263 impl Drop for RoundingModeGuard {
264 fn drop(&mut self) {
265 unsafe { fesetround(self.0) };
266 }
267 }
268
269 let _guard = RoundingModeGuard(fegetround());
271 fesetround(if UPPER { FE_UPWARD } else { FE_DOWNWARD });
272 operation(lhs, rhs)
273 }
274 #[cfg(any(
275 not(any(target_arch = "x86_64", target_arch = "aarch64")),
276 target_os = "windows"
277 ))]
278 alter_fp_rounding_mode_conservative::<UPPER, _>(lhs, rhs, operation)
279}
280
281#[cfg(test)]
282mod tests {
283 use super::{next_down, next_up};
284
285 #[cfg(all(
286 any(target_arch = "x86_64", target_arch = "aarch64"),
287 not(target_os = "windows")
288 ))]
289 #[test]
290 fn test_alter_fp_rounding_mode_restores_after_panic() {
291 use super::{FE_DOWNWARD, alter_fp_rounding_mode, fegetround, fesetround};
292 use crate::ScalarValue;
293
294 unsafe {
295 let original = fegetround();
296 fesetround(FE_DOWNWARD);
297
298 let result = std::panic::catch_unwind(|| {
299 alter_fp_rounding_mode::<true, _>(
300 &ScalarValue::Null,
301 &ScalarValue::Null,
302 |_, _| panic!("operation panicked"),
303 )
304 });
305
306 let restored = fegetround();
307 fesetround(original);
308
309 assert!(result.is_err());
310 assert_eq!(restored, FE_DOWNWARD);
311 }
312 }
313
314 #[test]
315 fn test_next_down() {
316 let x = 1.0f64;
317 let clamped = x.clamp(0.0, next_down(1.0f64));
319 assert!(clamped < 1.0);
320 assert_eq!(next_up(clamped), 1.0);
321 }
322
323 #[test]
324 fn test_next_up_small_positive() {
325 let value: f64 = 1.0;
326 let result = next_up(value);
327 assert_eq!(result, 1.0000000000000002);
328 }
329
330 #[test]
331 fn test_next_up_small_negative() {
332 let value: f64 = -1.0;
333 let result = next_up(value);
334 assert_eq!(result, -0.9999999999999999);
335 }
336
337 #[test]
338 fn test_next_up_pos_infinity() {
339 let value: f64 = f64::INFINITY;
340 let result = next_up(value);
341 assert_eq!(result, f64::INFINITY);
342 }
343
344 #[test]
345 fn test_next_up_nan() {
346 let value: f64 = f64::NAN;
347 let result = next_up(value);
348 assert!(result.is_nan());
349 }
350
351 #[test]
352 fn test_next_down_small_positive() {
353 let value: f64 = 1.0;
354 let result = next_down(value);
355 assert_eq!(result, 0.9999999999999999);
356 }
357
358 #[test]
359 fn test_next_down_small_negative() {
360 let value: f64 = -1.0;
361 let result = next_down(value);
362 assert_eq!(result, -1.0000000000000002);
363 }
364
365 #[test]
366 fn test_next_down_neg_infinity() {
367 let value: f64 = f64::NEG_INFINITY;
368 let result = next_down(value);
369 assert_eq!(result, f64::NEG_INFINITY);
370 }
371
372 #[test]
373 fn test_next_down_nan() {
374 let value: f64 = f64::NAN;
375 let result = next_down(value);
376 assert!(result.is_nan());
377 }
378
379 #[test]
380 fn test_next_up_small_positive_f32() {
381 let value: f32 = 1.0;
382 let result = next_up(value);
383 assert_eq!(result, 1.0000001);
384 }
385
386 #[test]
387 fn test_next_up_small_negative_f32() {
388 let value: f32 = -1.0;
389 let result = next_up(value);
390 assert_eq!(result, -0.99999994);
391 }
392
393 #[test]
394 fn test_next_up_pos_infinity_f32() {
395 let value: f32 = f32::INFINITY;
396 let result = next_up(value);
397 assert_eq!(result, f32::INFINITY);
398 }
399
400 #[test]
401 fn test_next_up_nan_f32() {
402 let value: f32 = f32::NAN;
403 let result = next_up(value);
404 assert!(result.is_nan());
405 }
406 #[test]
407 fn test_next_down_small_positive_f32() {
408 let value: f32 = 1.0;
409 let result = next_down(value);
410 assert_eq!(result, 0.99999994);
411 }
412 #[test]
413 fn test_next_down_small_negative_f32() {
414 let value: f32 = -1.0;
415 let result = next_down(value);
416 assert_eq!(result, -1.0000001);
417 }
418 #[test]
419 fn test_next_down_neg_infinity_f32() {
420 let value: f32 = f32::NEG_INFINITY;
421 let result = next_down(value);
422 assert_eq!(result, f32::NEG_INFINITY);
423 }
424 #[test]
425 fn test_next_down_nan_f32() {
426 let value: f32 = f32::NAN;
427 let result = next_down(value);
428 assert!(result.is_nan());
429 }
430
431 #[test]
432 fn test_next_up_neg_zero_f32() {
433 let value: f32 = -0.0;
434 let result = next_up(value);
435 assert_eq!(result, 0.0);
436 }
437
438 #[test]
439 fn test_next_down_zero_f32() {
440 let value: f32 = 0.0;
441 let result = next_down(value);
442 assert_eq!(result, -0.0);
443 }
444
445 #[test]
446 fn test_next_up_neg_zero_f64() {
447 let value: f64 = -0.0;
448 let result = next_up(value);
449 assert_eq!(result, 0.0);
450 }
451
452 #[test]
453 fn test_next_down_zero_f64() {
454 let value: f64 = 0.0;
455 let result = next_down(value);
456 assert_eq!(result, -0.0);
457 }
458}