4 // simple safe library to handle integer overflows when doing buffer size calculations
6 // - calculate data size using INTOVERFLOW_??? macros
7 // - compare: calculated-size <= INTOVERFLOW_NORMALIZE(buffersize)
9 // - all overflows (values > INTOVERFLOW_MAX) and errors are mapped to INTOVERFLOW_MAX
10 // - if any input of an operation is INTOVERFLOW_MAX, INTOVERFLOW_MAX will be returned
11 // - otherwise, regular arithmetics apply
13 #define INTOVERFLOW_MAX 2147483647
15 #define INTOVERFLOW_ADD(a,b) (((a) < INTOVERFLOW_MAX && (b) < INTOVERFLOW_MAX && (a) < INTOVERFLOW_MAX - (b)) ? ((a) + (b)) : INTOVERFLOW_MAX)
16 #define INTOVERFLOW_SUB(a,b) (((a) < INTOVERFLOW_MAX && (b) < INTOVERFLOW_MAX && (b) <= (a)) ? ((a) - (b)) : INTOVERFLOW_MAX)
17 #define INTOVERFLOW_MUL(a,b) (((a) < INTOVERFLOW_MAX && (b) < INTOVERFLOW_MAX && (a) < INTOVERFLOW_MAX / (b)) ? ((a) * (b)) : INTOVERFLOW_MAX)
18 #define INTOVERFLOW_DIV(a,b) (((a) < INTOVERFLOW_MAX && (b) < INTOVERFLOW_MAX && (b) > 0) ? ((a) / (b)) : INTOVERFLOW_MAX)
20 #define INTOVERFLOW_NORMALIZE(a) (((a) < INTOVERFLOW_MAX) ? (a) : (INTOVERFLOW_MAX - 1))