#include #include #include static int64_t formal_sat_add(int64_t i, int64_t j, int64_t min, int64_t max) { int64_t result = i + j; if (result < min) result = min; if (result > max) result = max; return result; } static int test_i8() { for (int64_t i = INT8_MIN; i <= INT8_MAX; ++i) for (int64_t j = INT8_MIN; j <= INT8_MAX; ++j) { int64_t expected = formal_sat_add(i, j, INT8_MIN, INT8_MAX); int8_t got = add_sat((int8_t)i, (int8_t)j); if (expected != got) { printf("%lld + %lld should be %lld, but got %lld!\n", (long long)i, (long long)j, (long long)expected, (long long)got); return -1; } } return 0; } static int test_i16() { for (int64_t i = INT16_MIN; i <= INT16_MAX; ++i) for (int64_t j = INT16_MIN; j <= INT16_MAX; ++j) { int64_t expected = formal_sat_add(i, j, INT16_MIN, INT16_MAX); int16_t got = add_sat((int16_t)i, (int16_t)j); if (expected != got) { printf("%lld + %lld should be %lld, but got %lld!\n", (long long)i, (long long)j, (long long)expected, (long long)got); return -1; } } return 0; } static int test_u16() { for (int64_t i = 0; i <= UINT16_MAX; ++i) for (int64_t j = 0; j <= UINT16_MAX; ++j) { int64_t expected = formal_sat_add(i, j, 0, UINT16_MAX); uint16_t got = add_sat((uint16_t)i, (uint16_t)j); if (expected != got) { printf("%lld + %lld should be %lld, but got %lld!\n", (long long)i, (long long)j, (long long)expected, (long long)got); return -1; } } return 0; } static int test_u8() { for (int64_t i = 0; i <= UINT8_MAX; ++i) for (int64_t j = 0; j <= UINT8_MAX; ++j) { int64_t expected = formal_sat_add(i, j, 0, UINT8_MAX); uint8_t got = add_sat((uint8_t)i, (uint8_t)j); if (expected != got) { printf("%lld + %lld should be %lld, but got %lld!\n", (long long)i, (long long)j, (long long)expected, (long long)got); return -1; } } return 0; } int main() { printf("add_sat\n"); /* these are still relatively easy to exhaustively check */ printf("i8...\n"); if (test_i8()) { printf("FAIL!\n"); return -1; } printf("u8...\n"); if (test_u8()) { printf("FAIL!\n"); return -1; } printf("i16...\n"); if (test_i16()) { printf("FAIL!\n"); return -1; } printf("u16...\n"); if (test_u16()) { printf("FAIL!\n"); return -1; } /* might add some random testing for 32/64 bit values, but presumably if * the narrower types work, the wider ones should work as well (assuming * I don't have some any silly typos or something) */ printf("OK!\n"); return 0; }