Skip to content

Commit

Permalink
util: add overflow safe unsigned addition function
Browse files Browse the repository at this point in the history
  • Loading branch information
martanne committed Feb 20, 2017
1 parent c22d020 commit a445d8f
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions util.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#ifndef UTIL_H
#define UTIL_H

#include <stdint.h>
#include <stdbool.h>

#define LENGTH(x) ((int)(sizeof (x) / sizeof *(x)))
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#define MAX(a, b) ((a) < (b) ? (b) : (a))
Expand All @@ -9,4 +12,15 @@
#define ISUTF8(c) (((c)&0xC0)!=0x80)
#define ISASCII(ch) ((unsigned char)ch < 0x80)

#if GCC_VERSION>=5004000 || CLANG_VERSION>=4000000
#define addu __builtin_add_overflow
#else
static inline bool addu(size_t a, size_t b, size_t *c) {
if (SIZE_MAX - a < b)
return false;
*c = a + b;
return true;
}
#endif

#endif

0 comments on commit a445d8f

Please sign in to comment.