safe_add.c 264 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include "safe_add.h"

uint16_t
safe_add(uint16_t x, int16_t delta)
{
	if (delta < 0) {
		uint16_t sub = -delta;
		if (x < sub) {
			return 0;
		}
		return x - sub;
	}

	uint16_t add = delta;
	if (UINT16_MAX - x < add) {
		return UINT16_MAX;
	}
	return x + add;
}