Peter Kasting | 2202c8e | 2017-09-13 20:40:59 | [diff] [blame] | 1 | // Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #ifndef BASE_NUMERICS_RANGES_H_ |
| 6 | #define BASE_NUMERICS_RANGES_H_ |
| 7 | |
| 8 | #include <algorithm> |
Miguel Casas-Sanchez | 92f328e | 2017-10-10 22:54:31 | [diff] [blame] | 9 | #include <cmath> |
Peter Kasting | 2202c8e | 2017-09-13 20:40:59 | [diff] [blame] | 10 | |
| 11 | namespace base { |
| 12 | |
Lei Zhang | e4839b6 | 2017-10-28 07:28:39 | [diff] [blame] | 13 | // To be replaced with std::clamp() from C++17, someday. |
| 14 | template <class T> |
| 15 | constexpr const T& ClampToRange(const T& value, const T& min, const T& max) { |
Peter Kasting | 2202c8e | 2017-09-13 20:40:59 | [diff] [blame] | 16 | return std::min(std::max(value, min), max); |
| 17 | } |
| 18 | |
Miguel Casas-Sanchez | 92f328e | 2017-10-10 22:54:31 | [diff] [blame] | 19 | template <typename T> |
| 20 | constexpr bool IsApproximatelyEqual(T lhs, T rhs, T tolerance) { |
| 21 | static_assert(std::is_arithmetic<T>::value, "Argument must be arithmetic"); |
| 22 | return std::abs(rhs - lhs) <= tolerance; |
| 23 | } |
| 24 | |
Peter Kasting | 2202c8e | 2017-09-13 20:40:59 | [diff] [blame] | 25 | } // namespace base |
| 26 | |
| 27 | #endif // BASE_NUMERICS_RANGES_H_ |