diff --git a/inc-c/ufn/ufn_round.h b/inc-c/ufn/ufn_round.h new file mode 100644 index 0000000..260ff0b --- /dev/null +++ b/inc-c/ufn/ufn_round.h @@ -0,0 +1,54 @@ + +#ifndef UFN_ROUND_H +#define UFN_ROUND_H + +#include + +int64_t ufn_floor_i64(int64_t value, int64_t stepping); +int64_t ufn_ceil_i64(int64_t value, int64_t stepping); + +uint64_t ufn_floor_pow2(uint64_t value); +uint64_t ufn_ceil_pow2(uint64_t value); + +#ifdef UFN_IMPLEMENTATION + +int64_t ufn_floor_i64(int64_t value, int64_t stepping) +{ + return value - (value % stepping); +} + +int64_t ufn_ceil_i64(int64_t value, int64_t stepping) +{ + return ufn_floor_i64(value, stepping) + stepping; +} + +uint64_t ufn_floor_pow2(uint64_t value) +{ + // Find highest-priority bit which is 1 + + int8_t bit_index = 63; + while(bit_index >= 0) + { + if(value & (1 << bit_index)) + { + break; + } + --bit_index; + } + return 1 << bit_index; +} + +uint64_t ufn_ceil_pow2(uint64_t value) +{ + uint64_t floored = ufn_floor_pow2(value); + if(value == floored) + { + return value; + } + return floored * 2; +} + +#endif // UFN_IMPLEMENTATION + +#endif // UFN_ROUND_H +