From: Yedidya Feldblum Date: Sat, 4 Nov 2017 22:34:00 +0000 (-0700) Subject: constexpr_clamp X-Git-Tag: v2017.11.06.00~1 X-Git-Url: http://plrg.eecs.uci.edu/git/?p=folly.git;a=commitdiff_plain;h=6ca1c3b610d25e267321f2d27c6a38496cc6f9c5 constexpr_clamp Summary: [Folly] `constexpr_clamp`. Like `std::clamp` (C++17). Reviewed By: Orvid Differential Revision: D6236825 fbshipit-source-id: 0f6c5dc9a955b148021ee6ed3e86201b53ae090c --- diff --git a/folly/ConstexprMath.h b/folly/ConstexprMath.h index 150acca3..7e14195c 100644 --- a/folly/ConstexprMath.h +++ b/folly/ConstexprMath.h @@ -44,6 +44,22 @@ constexpr T constexpr_min(T a, T b, Ts... ts) { return b < a ? constexpr_min(b, ts...) : constexpr_min(a, ts...); } +template +constexpr T const& +constexpr_clamp(T const& v, T const& lo, T const& hi, Less less) { + return less(v, lo) ? lo : less(hi, v) ? hi : v; +} + +template +constexpr T const& constexpr_clamp(T const& v, T const& lo, T const& hi) { + struct Less { + constexpr bool operator()(T const& a, T const& b) const { + return a < b; + } + }; + return constexpr_clamp(v, lo, hi, Less{}); +} + namespace detail { template diff --git a/folly/test/ConstexprMathTest.cpp b/folly/test/ConstexprMathTest.cpp index 6c0c71f9..1d732b7a 100644 --- a/folly/test/ConstexprMathTest.cpp +++ b/folly/test/ConstexprMathTest.cpp @@ -41,6 +41,18 @@ TEST_F(ConstexprMathTest, constexpr_max) { EXPECT_TRUE((std::is_same::value)); } +TEST_F(ConstexprMathTest, constexpr_clamp) { + constexpr auto lo = uint16_t(3); + constexpr auto hi = uint16_t(7); + constexpr auto x = folly::constexpr_clamp(uint16_t(2), lo, hi); + constexpr auto y = folly::constexpr_clamp(uint16_t(5), lo, hi); + constexpr auto z = folly::constexpr_clamp(uint16_t(8), lo, hi); + EXPECT_EQ(3, x); + EXPECT_EQ(5, y); + EXPECT_EQ(7, z); + EXPECT_TRUE((std::is_same::value)); +} + TEST_F(ConstexprMathTest, constexpr_abs_unsigned) { constexpr auto v = uint32_t(17); constexpr auto a = folly::constexpr_abs(v);