1293415Sdelphij#ifndef SAFECAST_H
2293415Sdelphij#define SAFECAST_H
3293415Sdelphij
4293415Sdelphij#include <limits.h>
5293415Sdelphijstatic inline int size2int_chk(size_t v)
6293415Sdelphij{
7293415Sdelphij	if (v > INT_MAX)
8293415Sdelphij		abort();
9293415Sdelphij	return (int)(v);
10293415Sdelphij}
11293415Sdelphij
12293415Sdelphijstatic inline int size2int_sat(size_t v)
13293415Sdelphij{
14293415Sdelphij	return (v > INT_MAX) ? INT_MAX : (int)v;
15293415Sdelphij}
16293415Sdelphij
17293415Sdelphij/* Compilers can emit warning about increased alignment requirements
18293415Sdelphij * when casting pointers. The impact is tricky: on machines where
19293415Sdelphij * alignment is just a performance issue (x86,x64,...) this might just
20293415Sdelphij * cause a performance penalty. On others, an address error can occur
21293415Sdelphij * and the process dies...
22293415Sdelphij *
23293415Sdelphij * Still, there are many cases where the pointer arithmetic and the
24293415Sdelphij * buffer alignment make sure this does not happen. OTOH, the compiler
25293415Sdelphij * doesn't know this and still emits warnings.
26293415Sdelphij *
27293415Sdelphij * The following cast macros are going through void pointers to tell
28293415Sdelphij * the compiler that there is no alignment requirement to watch.
29293415Sdelphij */
30293415Sdelphij#define UA_PTR(ptype,pval) ((ptype *)(void*)(pval))
31293415Sdelphij#define UAC_PTR(ptype,pval) ((const ptype *)(const void*)(pval))
32293415Sdelphij#define UAV_PTR(ptype,pval) ((volatile ptype *)(volatile void*)(pval))
33293415Sdelphij
34293415Sdelphij#endif
35