From 8fba851f4a8ec48fb3605e7f75f802bbdc2dcb4f Mon Sep 17 00:00:00 2001 From: Yedidya Feldblum Date: Wed, 13 Dec 2017 17:08:39 -0800 Subject: [PATCH] constexpr_ceil Summary: [Folly] `constexpr_ceil`, an integral rounding-up util. Reviewed By: Orvid Differential Revision: D6558042 fbshipit-source-id: 6b42add9bf2e3605baf71391130c2a2c88cc4385 --- folly/ConstexprMath.h | 7 +++++++ folly/test/ConstexprMathTest.cpp | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/folly/ConstexprMath.h b/folly/ConstexprMath.h index 7e14195c..5b0bc51d 100644 --- a/folly/ConstexprMath.h +++ b/folly/ConstexprMath.h @@ -115,4 +115,11 @@ constexpr T constexpr_log2(T t) { return detail::constexpr_log2(T(0), t); } +template +constexpr T constexpr_ceil(T t, T round) { + return round == T(0) + ? t + : ((t + (t < T(0) ? T(0) : round - T(1))) / round) * round; +} + } // namespace folly diff --git a/folly/test/ConstexprMathTest.cpp b/folly/test/ConstexprMathTest.cpp index 1d732b7a..7b60e8f0 100644 --- a/folly/test/ConstexprMathTest.cpp +++ b/folly/test/ConstexprMathTest.cpp @@ -122,3 +122,24 @@ TEST_F(ConstexprMathTest, constexpr_log2_64) { EXPECT_EQ(6ull, a); EXPECT_TRUE((std::is_same::value)); } + +TEST_F(ConstexprMathTest, constexpr_ceil) { + { + constexpr auto roundable = 20ull; + constexpr auto round = 6ull; + constexpr auto rounded = folly::constexpr_ceil(roundable, round); + EXPECT_EQ(24ull, rounded); + } + { + constexpr auto roundable = -20ll; + constexpr auto round = 6ll; + constexpr auto rounded = folly::constexpr_ceil(roundable, round); + EXPECT_EQ(-18ll, rounded); + } + { + constexpr auto roundable = -20ll; + constexpr auto round = 0ll; + constexpr auto rounded = folly::constexpr_ceil(roundable, round); + EXPECT_EQ(-20ll, rounded); + } +} -- 2.34.1