xref: /freebsd/lib/msun/src/s_truncl.c (revision a03411e84728e9b267056fd31c7d1d9d1dc1b01e)
1 /*
2  * ====================================================
3  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
4  *
5  * Developed at SunPro, a Sun Microsystems, Inc. business.
6  * Permission to use, copy, modify, and distribute this
7  * software is freely granted, provided that this notice
8  * is preserved.
9  * ====================================================
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 <float.h>
22 #include <math.h>
23 #include <stdint.h>
24 
25 #include "fpmath.h"
26 
27 #ifdef LDBL_IMPLICIT_NBIT
28 #define	MANH_SIZE	(LDBL_MANH_SIZE + 1)
29 #else
30 #define	MANH_SIZE	LDBL_MANH_SIZE
31 #endif
32 
33 static const long double huge = 1.0e300;
34 static const float zero[] = { 0.0, -0.0 };
35 
36 long double
37 truncl(long double x)
38 {
39 	union IEEEl2bits u = { .e = x };
40 	int e = u.bits.exp - LDBL_MAX_EXP + 1;
41 
42 	if (e < MANH_SIZE - 1) {
43 		if (e < 0) {			/* raise inexact if x != 0 */
44 			if (huge + x > 0.0)
45 				u.e = zero[u.bits.sign];
46 		} else {
47 			uint64_t m = ((1llu << MANH_SIZE) - 1) >> (e + 1);
48 			if (((u.bits.manh & m) | u.bits.manl) == 0)
49 				return (x);	/* x is integral */
50 			if (huge + x > 0.0) {	/* raise inexact flag */
51 				u.bits.manh &= ~m;
52 				u.bits.manl = 0;
53 			}
54 		}
55 	} else if (e < LDBL_MANT_DIG - 1) {
56 		uint64_t m = (uint64_t)-1 >> (64 - LDBL_MANT_DIG + e + 1);
57 		if ((u.bits.manl & m) == 0)
58 			return (x);	/* x is integral */
59 		if (huge + x > 0.0)		/* raise inexact flag */
60 			u.bits.manl &= ~m;
61 	}
62 	return (u.e);
63 }
64