1
0
Fork
You've already forked safemath
0
No description
  • C 99.4%
  • CMake 0.6%
2026年04月02日 20:24:10 +02:00
include Add README and license 2026年02月17日 19:28:50 +01:00
test Fix tests for 32-bit platforms 2026年04月02日 20:24:10 +02:00
.gitignore Initial commit 2025年11月08日 08:55:00 +01:00
CMakeLists.txt Add separate flag for enabling testing 2026年02月19日 19:42:08 +01:00
LICENSE Add README and license 2026年02月17日 19:28:50 +01:00
README.md Add README and license 2026年02月17日 19:28:50 +01:00

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);
}