xref: /freebsd/lib/msun/src/s_truncl.c (revision edf8578117e8844e02c0121147f45e4609b30680)
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  * From: @(#)s_floor.c 5.1 93/09/24
12  */
13 
14 #include <sys/cdefs.h>
15 /*
16  * truncl(x)
17  * Return x rounded toward 0 to integral value
18  * Method:
19  *	Bit twiddling.
20  * Exception:
21  *	Inexact flag raised if x not equal to truncl(x).
22  */
23 
24 #include <float.h>
25 #include <math.h>
26 #include <stdint.h>
27 
28 #include "fpmath.h"
29 
30 #ifdef LDBL_IMPLICIT_NBIT
31 #define	MANH_SIZE	(LDBL_MANH_SIZE + 1)
32 #else
33 #define	MANH_SIZE	LDBL_MANH_SIZE
34 #endif
35 
36 static const long double huge = 1.0e300;
37 static const float zero[] = { 0.0, -0.0 };
38 
39 long double
40 truncl(long double x)
41 {
42 	union IEEEl2bits u = { .e = x };
43 	int e = u.bits.exp - LDBL_MAX_EXP + 1;
44 
45 	if (e < MANH_SIZE - 1) {
46 		if (e < 0) {			/* raise inexact if x != 0 */
47 			if (huge + x > 0.0)
48 				u.e = zero[u.bits.sign];
49 		} else {
50 			uint64_t m = ((1llu << MANH_SIZE) - 1) >> (e + 1);
51 			if (((u.bits.manh & m) | u.bits.manl) == 0)
52 				return (x);	/* x is integral */
53 			if (huge + x > 0.0) {	/* raise inexact flag */
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 		if (huge + x > 0.0)		/* raise inexact flag */
63 			u.bits.manl &= ~m;
64 	}
65 	return (u.e);
66 }
67