fxp: Add FXP_INIT_PERCENT

This lets us specify fxp values easily in source.
This commit is contained in:
David Goldblatt 2020-12-08 15:28:28 -08:00 committed by David Goldblatt
parent caef4c2868
commit bdb7307ff2
2 changed files with 27 additions and 1 deletions

View File

@ -22,6 +22,7 @@
*/ */
typedef uint32_t fxp_t; typedef uint32_t fxp_t;
#define FXP_INIT_INT(x) ((x) << 16) #define FXP_INIT_INT(x) ((x) << 16)
#define FXP_INIT_PERCENT(pct) (((pct) << 16) / 100)
/* /*
* Amount of precision used in parsing and printing numbers. The integer bound * Amount of precision used in parsing and printing numbers. The integer bound

View File

@ -96,7 +96,8 @@ TEST_BEGIN(test_parse_valid) {
} }
TEST_END TEST_END
static void expect_parse_failure(const char *str) { static void
expect_parse_failure(const char *str) {
fxp_t result = FXP_INIT_INT(333); fxp_t result = FXP_INIT_INT(333);
char *end = (void *)0x123; char *end = (void *)0x123;
bool err = fxp_parse(&result, str, &end); bool err = fxp_parse(&result, str, &end);
@ -120,6 +121,29 @@ TEST_BEGIN(test_parse_invalid) {
} }
TEST_END TEST_END
static void
expect_init_percent(unsigned percent, const char *str) {
fxp_t result_init = FXP_INIT_PERCENT(percent);
fxp_t result_parse = xparse_fxp(str);
expect_u32_eq(result_init, result_parse,
"Expect representations of FXP_INIT_PERCENT(%u) and "
"fxp_parse(\"%s\") to be equal; got %x and %x",
percent, str, result_init, result_parse);
}
/*
* Every other test uses either parsing or FXP_INIT_INT; it gets tested in those
* ways. We need a one-off for the percent-based initialization, though.
*/
TEST_BEGIN(test_init_percent) {
expect_init_percent(100, "1");
expect_init_percent(75, ".75");
expect_init_percent(1, ".01");
expect_init_percent(50, ".5");
}
TEST_END
static void static void
expect_add(const char *astr, const char *bstr, const char* resultstr) { expect_add(const char *astr, const char *bstr, const char* resultstr) {
fxp_t a = xparse_fxp(astr); fxp_t a = xparse_fxp(astr);
@ -358,6 +382,7 @@ main(void) {
return test_no_reentrancy( return test_no_reentrancy(
test_parse_valid, test_parse_valid,
test_parse_invalid, test_parse_invalid,
test_init_percent,
test_add_simple, test_add_simple,
test_sub_simple, test_sub_simple,
test_mul_simple, test_mul_simple,