xref: /relibc/openlibm/src/s_truncl.c (revision 4f5112ea59cd2488b806c68b41e95dc31ebc8f0b)
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 "cdefs-compat.h"
15 //__FBSDID("$FreeBSD: src/lib/msun/src/s_truncl.c,v 1.9 2008/02/14 15:10:34 bde Exp $");
16 
17 /*
18  * truncl(x)
19  * Return x rounded toward 0 to integral value
20  * Method:
21  *	Bit twiddling.
22  * Exception:
23  *	Inexact flag raised if x not equal to truncl(x).
24  */
25 
26 #include <float.h>
27 #include <openlibm_math.h>
28 #include <stdint.h>
29 
30 #include "fpmath.h"
31 #include "math_private.h"
32 
33 #ifdef LDBL_IMPLICIT_NBIT
34 #define	MANH_SIZE	(LDBL_MANH_SIZE + 1)
35 #else
36 #define	MANH_SIZE	LDBL_MANH_SIZE
37 #endif
38 
39 static const long double huge = 1.0e300;
40 static const float zero[] = { 0.0, -0.0 };
41 
42 OLM_DLLEXPORT long double
43 truncl(long double x)
44 {
45 	union IEEEl2bits u = { .e = x };
46 	int e = u.bits.exp - LDBL_MAX_EXP + 1;
47 
48 	if (e < MANH_SIZE - 1) {
49 		if (e < 0) {			/* raise inexact if x != 0 */
50 			if (huge + x > 0.0)
51 				u.e = zero[u.bits.sign];
52 		} else {
53 			uint64_t m = ((1llu << MANH_SIZE) - 1) >> (e + 1);
54 			if (((u.bits.manh & m) | u.bits.manl) == 0)
55 				return (x);	/* x is integral */
56 			if (huge + x > 0.0) {	/* raise inexact flag */
57 				u.bits.manh &= ~m;
58 				u.bits.manl = 0;
59 			}
60 		}
61 	} else if (e < LDBL_MANT_DIG - 1) {
62 		uint64_t m = (uint64_t)-1 >> (64 - LDBL_MANT_DIG + e + 1);
63 		if ((u.bits.manl & m) == 0)
64 			return (x);	/* x is integral */
65 		if (huge + x > 0.0)		/* raise inexact flag */
66 			u.bits.manl &= ~m;
67 	}
68 	return (u.e);
69 }
70