summaryrefslogtreecommitdiff
path: root/git-compat-util.h
diff options
context:
space:
mode:
authorJonathan Nieder <jrnieder@gmail.com>2010-10-11 02:59:26 (GMT)
committerJunio C Hamano <gitster@pobox.com>2011-02-10 21:47:56 (GMT)
commit1368f65002bf39fdde7dd736a75ae35475184371 (patch)
treecb0d57165c5b1f710bb5e6499fa322185a8deb2f /git-compat-util.h
parenta8e4a5943a63c8fd4a3a9b70ccf4608bcc973707 (diff)
downloadgit-1368f65002bf39fdde7dd736a75ae35475184371.zip
git-1368f65002bf39fdde7dd736a75ae35475184371.tar.gz
git-1368f65002bf39fdde7dd736a75ae35475184371.tar.bz2
compat: helper for detecting unsigned overflow
The idiom (a + b < a) works fine for detecting that an unsigned integer has overflowed, but a more explicit unsigned_add_overflows(a, b) might be easier to read. Define such a macro, expanding roughly to ((a) < UINT_MAX - (b)). Because the expansion uses each argument only once outside of sizeof() expressions, it is safe to use with arguments that have side effects. Signed-off-by: Jonathan Nieder <jrnieder@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Diffstat (limited to 'git-compat-util.h')
-rw-r--r--git-compat-util.h6
1 files changed, 6 insertions, 0 deletions
diff --git a/git-compat-util.h b/git-compat-util.h
index d6d269f..9c23622 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -31,6 +31,9 @@
#define maximum_signed_value_of_type(a) \
(INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
+#define maximum_unsigned_value_of_type(a) \
+ (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
+
/*
* Signed integer overflow is undefined in C, so here's a helper macro
* to detect if the sum of two integers will overflow.
@@ -40,6 +43,9 @@
#define signed_add_overflows(a, b) \
((b) > maximum_signed_value_of_type(a) - (a))
+#define unsigned_add_overflows(a, b) \
+ ((b) > maximum_unsigned_value_of_type(a) - (a))
+
#ifdef __GNUC__
#define TYPEOF(x) (__typeof__(x))
#else