diff --git a/sys/sys/limits.h b/sys/sys/limits.h --- a/sys/sys/limits.h +++ b/sys/sys/limits.h @@ -90,6 +90,26 @@ #define QUAD_MIN (__QUAD_MIN) /* min value for a quad_t */ #endif +/* + * Programmatically determine the maximum value of + * an unsigned and signed type, without integer overflow. + * + * After determining the byte-size of the type, + * e.g. 2 for uint16_t, set the left-most bit. (0x8000) + * Set all bits but the highest by subtracting one. (0x7FFF) + * Shift all set bits left by one by way of muliply by 2. (0xFFFE) + * Finally, set the lowest bit by adding one. (0xFFFF) + * + * This is a portable way to programmatically determine + * the maximum value of an unsigned variable of arbitrary size. + */ +#define UTYPE_MAX(x) \ + ((((1ULL << (sizeof((x)) * 8 - 1)) - 1) * 2) + 1) + +#define TYPE_MAX(x) \ + ((((1ULL << (sizeof((x)) * 8 - 2)) - 1) * 2) + 1) + + #if __XSI_VISIBLE || __POSIX_VISIBLE >= 200809 #define LONG_BIT __LONG_BIT #define WORD_BIT __WORD_BIT