File: intoverflow.h

package info (click to toggle)
darkplaces 0~20180412~beta1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 18,200 kB
  • sloc: ansic: 176,886; makefile: 485; pascal: 455; perl: 372; objc: 245; sh: 102
file content (22 lines) | stat: -rw-r--r-- 1,214 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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