util: Add and use functions to calculate min and max int for a size

Many places need to know the maximum or minimum possible value for a
given size integer... so everyone just open-codes their favorite
version.  There is some potential to hit either undefined or
implementation-defined behavior, so having one version that Just Works
seems beneficial.

v2: Fix copy-and-pasted bug (INT64_MAX instead of INT64_MIN) in
u_intmin.  Noticed by CI.  Lol.  Rename functions
`s/u_(uint|int)(min|max)/u_\1N_\2/g`.  Suggested by Jason.  Add some
unit tests that would have caught the copy-and-paste bug before wasting
CI time.  Change the implementation of u_intN_min to use the same
pattern as stdint.h.  This avoids the integer division.  Noticed by
Jason.

v3: Add changes to convert_clear_color
(src/gallium/drivers/iris/iris_clear.c).  Suggested by Nanley.

Reviewed-by: Jason Ekstrand <jason@jlekstrand.net>
Suggested-by: Jason Ekstrand <jason@jlekstrand.net>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/12177>
This commit is contained in:
Ian Romanick
2021-08-02 16:43:52 -07:00
parent 08d6361591
commit 72259a870f
11 changed files with 146 additions and 48 deletions

View File

@@ -30,6 +30,8 @@
#include "c99_compat.h"
#include "c11_compat.h"
#include <stdint.h>
/* Compute the size of an array */
#ifndef ARRAY_SIZE
# define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
@@ -392,6 +394,30 @@ do { \
#define BITFIELD64_RANGE(b, count) \
(BITFIELD64_MASK((b) + (count)) & ~BITFIELD64_MASK(b))
static inline int64_t
u_intN_max(unsigned bit_size)
{
assert(bit_size <= 64 && bit_size > 0);
return INT64_MAX >> (64 - bit_size);
}
static inline int64_t
u_intN_min(unsigned bit_size)
{
/* On 2's compliment platforms, which is every platform Mesa is likely to
* every worry about, stdint.h generally calculated INT##_MIN in this
* manner.
*/
return (-u_intN_max(bit_size)) - 1;
}
static inline uint64_t
u_uintN_max(unsigned bit_size)
{
assert(bit_size <= 64 && bit_size > 0);
return UINT64_MAX >> (64 - bit_size);
}
/* TODO: In future we should try to move this to u_debug.h once header
* dependencies are reorganised to allow this.
*/