ranges.h 786 B

123456789101112131415161718192021222324252627
  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. #ifndef BASE_NUMERICS_RANGES_H_
  5. #define BASE_NUMERICS_RANGES_H_
  6. #include <algorithm>
  7. #include <cmath>
  8. namespace base {
  9. // To be replaced with std::clamp() from C++17, someday.
  10. template <class T>
  11. constexpr const T& ClampToRange(const T& value, const T& min, const T& max) {
  12. return std::min(std::max(value, min), max);
  13. }
  14. template <typename T>
  15. constexpr bool IsApproximatelyEqual(T lhs, T rhs, T tolerance) {
  16. static_assert(std::is_arithmetic<T>::value, "Argument must be arithmetic");
  17. return std::abs(rhs - lhs) <= tolerance;
  18. }
  19. } // namespace base
  20. #endif // BASE_NUMERICS_RANGES_H_