Skip to content

Commit edcd9a1

Browse files
committed
git-compat-util: introduce more size_t helpers
We will use them in the next commit. Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 4c76d16 commit edcd9a1

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

git-compat-util.h

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,14 @@
113113
#define unsigned_mult_overflows(a, b) \
114114
((a) && (b) > maximum_unsigned_value_of_type(a) / (a))
115115

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+
116124
#ifdef __GNUC__
117125
#define TYPEOF(x) (__typeof__(x))
118126
#else
@@ -862,6 +870,23 @@ static inline size_t st_sub(size_t a, size_t b)
862870
return a - b;
863871
}
864872

873+
static inline size_t st_left_shift(size_t a, unsigned shift)
874+
{
875+
if (unsigned_left_shift_overflows(a, shift))
876+
die("size_t overflow: %"PRIuMAX" << %u",
877+
(uintmax_t)a, shift);
878+
return a << shift;
879+
}
880+
881+
static inline unsigned long cast_size_t_to_ulong(size_t a)
882+
{
883+
if (a != (unsigned long)a)
884+
die("object too large to read on this platform: %"
885+
PRIuMAX" is cut off to %lu",
886+
(uintmax_t)a, (unsigned long)a);
887+
return (unsigned long)a;
888+
}
889+
865890
#ifdef HAVE_ALLOCA_H
866891
# include <alloca.h>
867892
# define xalloca(size) (alloca(size))

0 commit comments

Comments
 (0)