exp2l: Work around a NetBSD 10.0/i386 bug.
[gnulib.git] / lib / totalorderf.c
blobd235bc98bc4aac8e519273a80defe4a1e9f7fc00
1 /* Total order for 'float'
2 Copyright 2023-2024 Free Software Foundation, Inc.
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation, either version 3 of the
7 License, or (at your option) any later version.
9 This file is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Paul Eggert. */
19 #include <config.h>
21 /* Specification. */
22 #include <math.h>
24 int
25 totalorderf (float const *x, float const *y)
27 /* If the sign bits of *X and *Y differ, the one with non-zero sign bit
28 is "smaller" than the one with sign bit == 0. */
29 int xs = signbit (*x);
30 int ys = signbit (*y);
31 if (!xs != !ys)
32 return xs;
34 /* If one of *X, *Y is a NaN and the other isn't, the answer is easy
35 as well: the negative NaN is "smaller", the positive NaN is "greater"
36 than the other argument. */
37 int xn = isnanf (*x);
38 int yn = isnanf (*y);
39 if (!xn != !yn)
40 return !xn == !xs;
41 /* If none of *X, *Y is a NaN, the '<=' operator does the job, including
42 for -Infinity and +Infinity. */
43 if (!xn)
44 return *x <= *y;
46 /* At this point, *X and *Y are NaNs with the same sign bit. */
48 unsigned int extended_sign = -!!xs;
49 #if defined __hppa || defined __mips__ || defined __sh__
50 /* Invert the most significant bit of the mantissa field. Cf. snan.h. */
51 extended_sign ^= (1U << 22);
52 #endif
53 union { unsigned int i; float f; } volatile xu = {0}, yu = {0};
54 xu.f = *x;
55 yu.f = *y;
56 return (xu.i ^ extended_sign) <= (yu.i ^ extended_sign);