From: divverent Date: Wed, 30 Dec 2009 07:54:24 +0000 (+0000) Subject: add the intoverflow lib X-Git-Tag: xonotic-v0.1.0preview~909 X-Git-Url: https://git.rm.cloudns.org/?a=commitdiff_plain;h=535d9151f6a116574faee1964f810e541377bb11;p=xonotic%2Fdarkplaces.git add the intoverflow lib git-svn-id: svn://svn.icculus.org/twilight/trunk/darkplaces@9739 d7cf8633-e32d-0410-b094-e92efae38249 --- diff --git a/intoverflow.h b/intoverflow.h new file mode 100644 index 00000000..df906168 --- /dev/null +++ b/intoverflow.h @@ -0,0 +1,22 @@ +#ifndef INTOVERFLOW_H +#define INTOVERFLOW_H + +// simple safe library to handle integer overflows when doing buffer size calculations +// Usage: +// - calculate data size using INTOVERFLOW_??? macros +// - compare: calculated-size <= INTOVERFLOW_NORMALIZE(buffersize) +// Functionality: +// - all overflows (values > INTOVERFLOW_MAX) and errors are mapped to INTOVERFLOW_MAX +// - if any input of an operation is INTOVERFLOW_MAX, INTOVERFLOW_MAX will be returned +// - otherwise, regular arithmetics apply + +#define INTOVERFLOW_MAX 2147483647 + +#define INTOVERFLOW_ADD(a,b) (((a) < INTOVERFLOW_MAX && (b) < INTOVERFLOW_MAX && (a) < INTOVERFLOW_MAX - (b)) ? ((a) + (b)) : INTOVERFLOW_MAX) +#define INTOVERFLOW_SUB(a,b) (((a) < INTOVERFLOW_MAX && (b) < INTOVERFLOW_MAX && (b) <= (a)) ? ((a) - (b)) : INTOVERFLOW_MAX) +#define INTOVERFLOW_MUL(a,b) (((a) < INTOVERFLOW_MAX && (b) < INTOVERFLOW_MAX && (a) < INTOVERFLOW_MAX / (b)) ? ((a) * (b)) : INTOVERFLOW_MAX) +#define INTOVERFLOW_DIV(a,b) (((a) < INTOVERFLOW_MAX && (b) < INTOVERFLOW_MAX && (b) > 0) ? ((a) / (b)) : INTOVERFLOW_MAX) + +#define INTOVERFLOW_NORMALIZE(a) (((a) < INTOVERFLOW_MAX) ? (a) : (INTOVERFLOW_MAX - 1)) + +#endif