git-compat-util: introduce more size_t helpers

We will use them in the next commit. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Johannes Schindelin committed Nov 2, 2021 at 15:46 UTC e2ffeae3f6795939e1af9f8e2b5fa151343eec66
1 file changed +25
git-compat-util.h
+25
@@ -113,6 +113,14 @@
113 #define unsigned_mult_overflows(a, b) \
114 ((a) && (b) > maximum_unsigned_value_of_type(a) / (a))
115
116 +/*
117 + * Returns true if the left shift of "a" by "shift" bits will
118 + * overflow. The type of "a" must be unsigned.
119 + */
120 +#define unsigned_left_shift_overflows(a, shift) \
121 + ((shift) < bitsizeof(a) && \
122 + (a) > maximum_unsigned_value_of_type(a) >> (shift))
123 +
124 #ifdef __GNUC__
125 #define TYPEOF(x) (__typeof__(x))
126 #else
@@ -859,6 +867,23 @@ static inline size_t st_sub(size_t a, size_t b)
867 return a - b;
868 }
869
870 +static inline size_t st_left_shift(size_t a, unsigned shift)
871 +{
872 + if (unsigned_left_shift_overflows(a, shift))
873 + die("size_t overflow: %"PRIuMAX" << %u",
874 + (uintmax_t)a, shift);
875 + return a << shift;
876 +}
877 +
878 +static inline unsigned long cast_size_t_to_ulong(size_t a)
879 +{
880 + if (a != (unsigned long)a)
881 + die("object too large to read on this platform: %"
882 + PRIuMAX" is cut off to %lu",
883 + (uintmax_t)a, (unsigned long)a);
884 + return (unsigned long)a;
885 +}
886 +
887 #ifdef HAVE_ALLOCA_H
888 # include <alloca.h>
889 # define xalloca(size) (alloca(size))