Re: [PATCH v3 6/8] git-compat-util: introduce more size_t helpers
- From
Junio C Hamano <gitster@pobox.com>
- Date
- Oct 29, 2021, 23:10 UTC
- Message-ID
- <xmqqcznnh1gc.fsf@gitster.g>
- In-Reply-To
- <18419070c29aef85c266f01174f436566bf792fd.1635515959.git.gitgitgadget@gmail.com>
"Johannes Schindelin via GitGitGadget" <gitgitgadget@gmail.com> writes:
Show 7 quoted lines
> +/* > + * Returns true if the left shift of "a" by "shift" bits will > + * overflow. The type of "a" must be unsigned. > + */ > +#define unsigned_left_shift_overflows(a, shift) \ > + ((shift) < bitsizeof(a) && \ > + (a) > maximum_unsigned_value_of_type(a) >> (shift))
Cute. So somebody asks
if (unsigned_left_shift_overflows(a, 100)
and they get "you are unsafe, regardless of the value of a, you get an overflow". Makes perfect sensen.
Show 14 quoted lines
> #ifdef __GNUC__
> #define TYPEOF(x) (__typeof__(x))
> #else
> @@ -859,6 +867,23 @@ static inline size_t st_sub(size_t a, size_t b)
> return a - b;
> }
>
> +static inline size_t st_left_shift(size_t a, unsigned shift)
> +{
> + if (unsigned_left_shift_overflows(a, shift))
> + die("size_t overflow: %"PRIuMAX" << %u",
> + (uintmax_t)a, shift);
> + return a << shift;
> +}Makes sense.
Show 12 quoted lines
> +static inline unsigned long cast_size_t_to_ulong(size_t a)
> +{
> + if (a != (unsigned long)a)
> + die("object too large to read on this platform: %"
> + PRIuMAX" is cut off to %lu",
> + (uintmax_t)a, (unsigned long)a);
> + return (unsigned long)a;
> +}
> +
> #ifdef HAVE_ALLOCA_H
> # include <alloca.h>
> # define xalloca(size) (alloca(size))