From 67a3e016e1da3fa14923ae2e9565db2756e3389d Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Mon, 16 Mar 2020 13:51:45 +1100 Subject: [PATCH] maths: document `log2` and `log2up` --- maths.cpp | 12 ------------ maths.hpp | 20 ++++++++++++++++---- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/maths.cpp b/maths.cpp index 5a3fcb0d..2e2f767f 100644 --- a/maths.cpp +++ b/maths.cpp @@ -11,18 +11,6 @@ #include -/////////////////////////////////////////////////////////////////////////////// -template -T -cruft::log2up (T v) -{ - return log2 ((v << 1) - 1); -} - -template uint32_t cruft::log2up (uint32_t); -template uint64_t cruft::log2up (uint64_t); - - /////////////////////////////////////////////////////////////////////////////// // Simple instantiations. Some functions aren't used internally to the library // so it's easier to instantiate early and check for broken code at library diff --git a/maths.hpp b/maths.hpp index 824233a0..df62051b 100644 --- a/maths.hpp +++ b/maths.hpp @@ -183,12 +183,18 @@ namespace cruft { } - //----------------------------------------------------------------------------- - // Logarithms + /////////////////////////////////////////////////////////////////////////////// + /// Calculate the base-2 logarithm of an integer, truncating to the next + /// lowest integer. + /// + /// `val` must be strictly greater than zero, otherwise the results are + /// undefined. template constexpr T log2 (T val) { + assert (val > 0); + T tally = 0; while (val >>= 1) ++tally; @@ -196,10 +202,16 @@ namespace cruft { } - //------------------------------------------------------------------------- + ///------------------------------------------------------------------------ + /// Calculates the base-2 logarithm of an integer, rounding up to the next + /// highest integer. template T - log2up (T val); + log2up (T val) + { + + return log2 ((val << 1) - 1); + } ///////////////////////////////////////////////////////////////////////////////