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