common: add a helper to round up to next power of 2

This is something relatively frequently needed, and there must be half a
dozen ad-hoc implementations in mpv. The next commit uses this, the
suspected duplicate implementations are hiding.
This commit is contained in:
wm4 2019-11-06 21:35:49 +01:00
parent 48fc642e0c
commit abb089431d
2 changed files with 15 additions and 0 deletions

View File

@ -336,3 +336,17 @@ unsigned int mp_log2(uint32_t v)
return 0;
#endif
}
// If a power of 2, return it, otherwise return the next highest one, or 0.
// mp_round_next_power_of_2(65) == 128
// mp_round_next_power_of_2(64) == 64
// mp_round_next_power_of_2(0) == 1
// mp_round_next_power_of_2(UINT32_MAX) == 0
uint32_t mp_round_next_power_of_2(uint32_t v)
{
for (int n = 0; n < 30; n++) {
if ((1 << n) >= v)
return 1 << n;
}
return 0;
}

View File

@ -89,6 +89,7 @@ bool mp_rect_contains(struct mp_rect *rc, int x, int y);
bool mp_rect_equals(struct mp_rect *rc1, struct mp_rect *rc2);
unsigned int mp_log2(uint32_t v);
uint32_t mp_round_next_power_of_2(uint32_t v);
int mp_snprintf_cat(char *str, size_t size, const char *format, ...)
PRINTF_ATTRIBUTE(3, 4);