constexpr_ceil
authorYedidya Feldblum <yfeldblum@fb.com>
Thu, 14 Dec 2017 01:08:39 +0000 (17:08 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Thu, 14 Dec 2017 01:09:37 +0000 (17:09 -0800)
Summary: [Folly] `constexpr_ceil`, an integral rounding-up util.

Reviewed By: Orvid

Differential Revision: D6558042

fbshipit-source-id: 6b42add9bf2e3605baf71391130c2a2c88cc4385

folly/ConstexprMath.h
folly/test/ConstexprMathTest.cpp

index 7e14195c5009eabda1b0c9dc8fe2c878c5f5b79d..5b0bc51d57d514f713a8b6932fdef62ac012e244 100644 (file)
@@ -115,4 +115,11 @@ constexpr T constexpr_log2(T t) {
   return detail::constexpr_log2(T(0), t);
 }
 
+template <typename T>
+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
index 1d732b7ac9078263386935256615d3035c127bae..7b60e8f06e9c064b0c2220587b039b2866a968d0 100644 (file)
@@ -122,3 +122,24 @@ TEST_F(ConstexprMathTest, constexpr_log2_64) {
   EXPECT_EQ(6ull, a);
   EXPECT_TRUE((std::is_same<decltype(v), decltype(a)>::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);
+  }
+}