initial cmath code and minor libm.h update
[libm] / src / math / truncl.c
1 /* origin: FreeBSD /usr/src/lib/msun/src/s_truncl.c */
2 /*
3  * ====================================================
4  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
5  *
6  * Developed at SunPro, a Sun Microsystems, Inc. business.
7  * Permission to use, copy, modify, and distribute this
8  * software is freely granted, provided that this notice
9  * is preserved.
10  * ====================================================
11  */
12 /*
13  * truncl(x)
14  * Return x rounded toward 0 to integral value
15  * Method:
16  *      Bit twiddling.
17  * Exception:
18  *      Inexact flag raised if x not equal to truncl(x).
19  */
20
21 #include "libm.h"
22
23 #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
24 long double truncl(long double x)
25 {
26         return trunc(x);
27 }
28 #elif (LDBL_MANT_DIG == 64 || LDBL_MANT_DIG == 113) && LDBL_MAX_EXP == 16384
29 #ifdef LDBL_IMPLICIT_NBIT
30 #define MANH_SIZE       (LDBL_MANH_SIZE + 1)
31 #else
32 #define MANH_SIZE       LDBL_MANH_SIZE
33 #endif
34
35 static const long double huge = 1.0e300;
36 static const float zero[] = { 0.0, -0.0 };
37
38 long double truncl(long double x)
39 {
40         union IEEEl2bits u = { .e = x };
41         int e = u.bits.exp - LDBL_MAX_EXP + 1;
42
43         if (e < MANH_SIZE - 1) {
44                 if (e < 0) {
45                         /* raise inexact if x != 0 */
46                         if (huge + x > 0.0)
47                                 u.e = zero[u.bits.sign];
48                 } else {
49                         uint64_t m = ((1llu << MANH_SIZE) - 1) >> (e + 1);
50                         if (((u.bits.manh & m) | u.bits.manl) == 0)
51                                 return x;     /* x is integral */
52                         /* raise inexact */
53                         if (huge + x > 0.0) {
54                                 u.bits.manh &= ~m;
55                                 u.bits.manl = 0;
56                         }
57                 }
58         } else if (e < LDBL_MANT_DIG - 1) {
59                 uint64_t m = (uint64_t)-1 >> (64 - LDBL_MANT_DIG + e + 1);
60                 if ((u.bits.manl & m) == 0)
61                         return x;     /* x is integral */
62                 /* raise inexact */
63                 if (huge + x > 0.0)
64                         u.bits.manl &= ~m;
65         }
66         return u.e;
67 }
68 #endif