diff --git a/include/stdex/math.hpp b/include/stdex/math.hpp index dc86da7ef..b62ad2886 100644 --- a/include/stdex/math.hpp +++ b/include/stdex/math.hpp @@ -67,6 +67,34 @@ namespace stdex throw std::invalid_argument("add overflow"); } + /// + /// Rounds number down and aligns it to have given number of lower bits zero. + /// + /// \param a Number to round down + /// \param n Number of lower bits to be zero after rounding + /// + /// \return The biggest number lower or equal to a that has n lower bits zero + /// + inline constexpr size_t align_down(size_t a, int n) + { + const size_t mask = SIZE_MAX << n; + return a & mask; + } + + /// + /// Rounds number up and aligns it to have given number of lower bits zero. It throws on overflow. + /// + /// \param a Number to round up + /// \param n Number of lower bits to be zero after rounding + /// + /// \return The first number greater or equal to a that has n lower bits zero + /// + inline constexpr size_t align_up(size_t a, int n) + { + const size_t mask = SIZE_MAX << n; + return add(a, ~mask) & mask; + } + /// /// Bitwise rotates left ///