]> git.ipfire.org Git - thirdparty/git.git/commit - cache.h
msvc: avoid using minus operator on unsigned types
authorJohannes Schindelin <johannes.schindelin@gmx.de>
Fri, 4 Oct 2019 15:09:26 +0000 (08:09 -0700)
committerJunio C Hamano <gitster@pobox.com>
Sun, 6 Oct 2019 00:07:44 +0000 (09:07 +0900)
commitc097b95a260b5a870c26a61d032169b70769e31a
treebfe3d31510127deb68458f4147b9424e802dee72
parentdbcd970c27ba42ab09073211f858b1a89c7f8300
msvc: avoid using minus operator on unsigned types

MSVC complains about this with `-Wall`, which can be taken as a sign
that this is indeed a real bug. The symptom is:

C4146: unary minus operator applied to unsigned type, result
still unsigned

Let's avoid this warning in the minimal way, e.g. writing `-1 -
<unsigned value>` instead of `-<unsigned value> - 1`.

Note that the change in the `estimate_cache_size()` function is
needed because MSVC considers the "return type" of the `sizeof()`
operator to be `size_t`, i.e. unsigned, and therefore it cannot be
negated using the unary minus operator.

Even worse, that arithmetic is doing extra work, in vain. We want to
calculate the entry extra cache size as the difference between the
size of the `cache_entry` structure minus the size of the
`ondisk_cache_entry` structure, padded to the appropriate alignment
boundary.

To that end, we start by assigning that difference to the `per_entry`
variable, and then abuse the `len` parameter of the
`align_padding_size()` macro to take the negative size of the ondisk
entry size. Essentially, we try to avoid passing the already calculated
difference to that macro by passing the operands of that difference
instead, when the macro expects operands of an addition:

#define align_padding_size(size, len) \
((size + (len) + 8) & ~7) - (size + len)

Currently, we pass A and -B to that macro instead of passing A - B and
0, where A - B is already stored in the `per_entry` variable, ready to
be used.

This is neither necessary, nor intuitive. Let's fix this, and have code
that is both easier to read and that also does not trigger MSVC's
warning.

While at it, we take care of reporting overflows (which are unlikely,
but hey, defensive programming is good!).

We _also_ take pains of casting the unsigned value to signed: otherwise,
the signed operand (i.e. the `-1`) would be cast to unsigned before
doing the arithmetic.

Helped-by: Denton Liu <liu.denton@gmail.com>
Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
cache.h
read-cache.c
sha1-lookup.c