X-Git-Url: http://git.tuebingen.mpg.de/?p=paraslash.git;a=blobdiff_plain;f=mood.c;h=c06f695c36f8d29664cc48e2e877a7d758702913;hp=584c46b8fa375f24d2f87492d44f67ac902fa98b;hb=177ea8ea46918a925c0d2d8a07e7fbe9f478a40c;hpb=3d3a2f50a05501cf27f1155629799953f952bd4b diff --git a/mood.c b/mood.c index 584c46b8..c06f695c 100644 --- a/mood.c +++ b/mood.c @@ -93,32 +93,60 @@ struct mood { */ static struct mood *current_mood; -/** - * Rough approximation to sqrt. +/* + * Find the position of the most-significant set bit. * - * \param x Integer of which to calculate the sqrt. + * Copied and slightly adapted from the linux source tree, version 4.9.39 + * (2017-07). + */ +__a_const static uint32_t fls64(uint64_t v) +{ + int n = 63; + const uint64_t ones = ~(uint64_t)0U; + + if ((v & (ones << 32)) == 0) { + n -= 32; + v <<= 32; + } + if ((v & (ones << (64 - 16))) == 0) { + n -= 16; + v <<= 16; + } + if ((v & (ones << (64 - 8))) == 0) { + n -= 8; + v <<= 8; + } + if ((v & (ones << (64 - 4))) == 0) { + n -= 4; + v <<= 4; + } + if ((v & (ones << (64 - 2))) == 0) { + n -= 2; + v <<= 2; + } + if ((v & (ones << (64 - 1))) == 0) + n -= 1; + return n; +} + +/* + * Compute the integer square root floor(sqrt(x)). * - * \return An integer res with res * res <= x. + * Taken 2007 from the linux source tree. */ __a_const static uint64_t int_sqrt(uint64_t x) { - uint64_t op, res, one = 1; - op = x; - res = 0; - - one = one << 62; - while (one > op) - one >>= 2; + uint64_t op = x, res = 0, one = 1; + one = one << (fls64(x) & ~one); while (one != 0) { if (op >= res + one) { op = op - (res + one); - res = res + 2 * one; + res = res + 2 * one; } res /= 2; one /= 4; } -// PARA_NOTICE_LOG("sqrt(%llu) = %llu\n", x, res); return res; }