diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index c70aa2d6dd..457c8ef37f 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -215,17 +215,6 @@ void HighFrequencyLoopRequester::stop() { } bool HighFrequencyLoopRequester::is_high_frequency() { return high_freq_num_requests > 0; } -template T clamp(const T val, const T min, const T max) { - if (val < min) - return min; - if (val > max) - return max; - return val; -} -template uint8_t clamp(uint8_t, uint8_t, uint8_t); -template float clamp(float, float, float); -template int clamp(int, int, int); - float lerp(float completion, float start, float end) { return start + (end - start) * completion; } bool str_startswith(const std::string &full, const std::string &start) { return full.rfind(start, 0) == 0; } diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 4699e8071c..bbe6b49827 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -58,15 +58,6 @@ class HighFrequencyLoopRequester { bool started_{false}; }; -/** Clamp the value between min and max. - * - * @param val The value. - * @param min The minimum value. - * @param max The maximum value. - * @return val clamped in between min and max. - */ -template T clamp(T val, T min, T max); - /** Linearly interpolate between end start and end by completion. * * @tparam T The input/output typename. @@ -277,6 +268,18 @@ using std::is_trivially_copyable; template struct is_trivially_copyable : public std::integral_constant {}; #endif +// std::clamp from C++17 +#if __cpp_lib_clamp >= 201603 +using std::clamp; +#else +template constexpr const T &clamp(const T &v, const T &lo, const T &hi, Compare comp) { + return comp(v, lo) ? lo : comp(hi, v) ? hi : v; +} +template constexpr const T &clamp(const T &v, const T &lo, const T &hi) { + return clamp(v, lo, hi, std::less{}); +} +#endif + // std::bit_cast from C++20 #if __cpp_lib_bit_cast >= 201806 using std::bit_cast;