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