Re: [PATCH v2] do not depend on signed integer overflow

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, Oct 5, 2010 at 12:33 AM, Jonathan Nieder <jrnieder@xxxxxxxxx> wrote:
> Erik Faye-Lund wrote:
>
>> +++ b/git-compat-util.h
>> @@ -28,6 +28,15 @@
>>  #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
>>  #define bitsizeof(x)  (CHAR_BIT * sizeof(x))
>>
>> +/*
>> + * Signed integer overflow is undefined in C, so here's a helper macro
>> + * to detect if the sum of two integers will overflow. The bitsize to
>> + * overflow at is taken from the first parameter, which must be zero
>> + * or positive.
>> + */
>> +#define signed_add_overflows(a, b) \
>> +    ((b) > ((INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a))) - (a)))
>
> Yes, I still like it.  This could be made closer to self-documenting
> like so:
>
> #define maximum_signed_value_of_type(a) \
>        (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
>
> /*
>  * Signed overflow is undefined in C, so here's a helper macro
>  * to detect if the sum of two signed integers will overflow.
>  *
>  * Requires: a >= 0, typeof(a) equals typeof(b)
>  */
> #define signed_add_overflows(a, b) \
>        ((b) > maximum_signed_value_of_type(a) - (a))
>

I like that. Thanks for the suggestion, I'll roll a new version.
--
To unsubscribe from this list: send the line "unsubscribe git" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html


[Index of Archives]     [Linux Kernel Development]     [Gcc Help]     [IETF Annouce]     [DCCP]     [Netdev]     [Networking]     [Security]     [V4L]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Linux SCSI]     [Fedora Users]