Re: [PATCH] hex: use unsigned index for ring buffer
- From
Junio C Hamano <gitster@pobox.com>
- Date
- Oct 26, 2016, 17:53 UTC
- Message-ID
- <xmqqlgxbatec.fsf@gitster.mtv.corp.google.com>
- In-Reply-To
- <3c95a89a-2a9b-2856-42a1-6b994f2e31cd@web.de>
René Scharfe <l.s.r@web.de> writes:
> Actually I didn't sign-off on purpose originally. But OK, let's keep > the version below. I just feel strangely sad seeing that concise magic > go. Nevermind.
I actually share the sadness, too, but let's be stupid and obvious here.
Thanks.
Show 53 quoted lines
>
> Signed-off-by: Rene Scharfe <l.s.r@web.de>
>
>> -- >8 --
>> From: René Scharfe <l.s.r@web.de>
>> Date: Sun, 23 Oct 2016 19:57:30 +0200
>> Subject: [PATCH] hex: make wraparound of the index into ring-buffer explicit
>>
>> Overflow is defined for unsigned integers, but not for signed ones.
>>
>> We could make the ring-buffer index in sha1_to_hex() and
>> get_pathname() unsigned to be on the safe side to resolve this, but
>> let's make it explicit that we are wrapping around at whatever the
>> number of elements the ring-buffer has. The compiler is smart enough
>> to turn modulus into bitmask for these codepaths that use
>> ring-buffers of a size that is a power of 2.
>>
>> Signed-off-by: René Scharfe <l.s.r@web.de>
>> Signed-off-by: Junio C Hamano <gitster@pobox.com>
>> ---
>> hex.c | 3 ++-
>> path.c | 3 ++-
>> 2 files changed, 4 insertions(+), 2 deletions(-)
>>
>> diff --git a/hex.c b/hex.c
>> index ab2610e498..845b01a874 100644
>> --- a/hex.c
>> +++ b/hex.c
>> @@ -78,7 +78,8 @@ char *sha1_to_hex(const unsigned char *sha1)
>> {
>> static int bufno;
>> static char hexbuffer[4][GIT_SHA1_HEXSZ + 1];
>> - return sha1_to_hex_r(hexbuffer[3 & ++bufno], sha1);
>> + bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
>> + return sha1_to_hex_r(hexbuffer[bufno], sha1);
>> }
>>
>> char *oid_to_hex(const struct object_id *oid)
>> diff --git a/path.c b/path.c
>> index fe3c4d96c6..9bfaeda207 100644
>> --- a/path.c
>> +++ b/path.c
>> @@ -24,7 +24,8 @@ static struct strbuf *get_pathname(void)
>> STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
>> };
>> static int index;
>> - struct strbuf *sb = &pathname_array[3 & ++index];
>> + struct strbuf *sb = &pathname_array[index];
>> + index = (index + 1) % ARRAY_SIZE(pathname_array);
>> strbuf_reset(sb);
>> return sb;
>> }
>>