No description
- C 99.4%
- CMake 0.6%
| include | Add README and license | |
| test | Fix tests for 32-bit platforms | |
| .gitignore | Initial commit | |
| CMakeLists.txt | Add separate flag for enabling testing | |
| LICENSE | Add README and license | |
| README.md | Add README and license | |
safemath
Header-only C library implementing checked integer arithmetic operations.
Features
It exposes portable inline functions performing
- type-casting
- addition
- subtraction
- multiplication
- division
- modulo
- bitshift left
- bitshift right
on (u)int8_t, (u)int16_t, (u)int32_t, (u)int64_t
and - if SIZE_MAX is defined - size_t types.
Note: Typecasting functions only exist for narrowing conversion and sign conversions
(i.e. uint64_t to uint8_t, uint32_t to int32_t).
The functions check and report overflows, underflows and division by zero where applicable.
They do not just report if an exceptional condition occurred, but what
type occurred. This for example allows for clamping signed values to their extreme values.
Usage
#include <assert.h>
#include <safemath.h>
void unsigned_example(void) {
uint8_t sum;
uint8_t summand1 = 127u, summand2 = 128u;
safemath_result_t res;
/*
* All safemath functions return a safemath_result_t,
* reporting the outcome of the operation.
*/
res = safemathaddU8(&sum, summand1, summand2);
/* No overflow */
assert(255u == sum);
assert(SAFEMATH_OK == res);
summand1++;
res = safemathaddU8(&sum, summand1, summand2);
/* This operation overflowed */
assert(SAFEMATH_OVERFLOW == res);
}
void signed_example(void) {
int16_t product;
int16_t factor1 = 300, factor2 = 200;
safemath_result_t res;
res = safemathmulI16(&product, factor1, factor2);
/* No overflow */
assert(60000 == product);
assert(SAFEMATH_OK == res);
factor2 = 300;
res = safemathmulI16(&product, factor1, factor2);
/* Overflow */
assert(SAFEMATH_OVERFLOW == res);
factor1 = -250;
/* Underflow */
assert(SAFEMATH_UNDERFLOW == res);
}