From 406d14746fa520c6e4de2e6c40c0ab9b30c9eee5 Mon Sep 17 00:00:00 2001 From: Simon Rozman Date: Tue, 27 May 2025 11:52:14 +0200 Subject: [PATCH] math: add align_up/down Signed-off-by: Simon Rozman --- include/stdex/math.hpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) 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 ///