xref: /freebsd/contrib/ntp/include/safecast.h (revision 009e81b16465ea457c0e63fd49fe77f47cc27a5a)
1*3311ff84SXin LI #ifndef SAFECAST_H
2*3311ff84SXin LI #define SAFECAST_H
3*3311ff84SXin LI 
4*3311ff84SXin LI #include <limits.h>
size2int_chk(size_t v)5*3311ff84SXin LI static inline int size2int_chk(size_t v)
6*3311ff84SXin LI {
7*3311ff84SXin LI 	if (v > INT_MAX)
8*3311ff84SXin LI 		abort();
9*3311ff84SXin LI 	return (int)(v);
10*3311ff84SXin LI }
11*3311ff84SXin LI 
size2int_sat(size_t v)12*3311ff84SXin LI static inline int size2int_sat(size_t v)
13*3311ff84SXin LI {
14*3311ff84SXin LI 	return (v > INT_MAX) ? INT_MAX : (int)v;
15*3311ff84SXin LI }
16*3311ff84SXin LI 
17*3311ff84SXin LI /* Compilers can emit warning about increased alignment requirements
18*3311ff84SXin LI  * when casting pointers. The impact is tricky: on machines where
19*3311ff84SXin LI  * alignment is just a performance issue (x86,x64,...) this might just
20*3311ff84SXin LI  * cause a performance penalty. On others, an address error can occur
21*3311ff84SXin LI  * and the process dies...
22*3311ff84SXin LI  *
23*3311ff84SXin LI  * Still, there are many cases where the pointer arithmetic and the
24*3311ff84SXin LI  * buffer alignment make sure this does not happen. OTOH, the compiler
25*3311ff84SXin LI  * doesn't know this and still emits warnings.
26*3311ff84SXin LI  *
27*3311ff84SXin LI  * The following cast macros are going through void pointers to tell
28*3311ff84SXin LI  * the compiler that there is no alignment requirement to watch.
29*3311ff84SXin LI  */
30*3311ff84SXin LI #define UA_PTR(ptype,pval) ((ptype *)(void*)(pval))
31*3311ff84SXin LI #define UAC_PTR(ptype,pval) ((const ptype *)(const void*)(pval))
32*3311ff84SXin LI #define UAV_PTR(ptype,pval) ((volatile ptype *)(volatile void*)(pval))
33*3311ff84SXin LI 
34*3311ff84SXin LI #endif
35