xref: /aosp_15_r20/external/libchrome/base/numerics/ranges.h (revision 635a864187cb8b6c713ff48b7e790a6b21769273)
1*635a8641SAndroid Build Coastguard Worker // Copyright 2017 The Chromium Authors. All rights reserved.
2*635a8641SAndroid Build Coastguard Worker // Use of this source code is governed by a BSD-style license that can be
3*635a8641SAndroid Build Coastguard Worker // found in the LICENSE file.
4*635a8641SAndroid Build Coastguard Worker 
5*635a8641SAndroid Build Coastguard Worker #ifndef BASE_NUMERICS_RANGES_H_
6*635a8641SAndroid Build Coastguard Worker #define BASE_NUMERICS_RANGES_H_
7*635a8641SAndroid Build Coastguard Worker 
8*635a8641SAndroid Build Coastguard Worker #include <algorithm>
9*635a8641SAndroid Build Coastguard Worker #include <cmath>
10*635a8641SAndroid Build Coastguard Worker 
11*635a8641SAndroid Build Coastguard Worker namespace base {
12*635a8641SAndroid Build Coastguard Worker 
13*635a8641SAndroid Build Coastguard Worker // To be replaced with std::clamp() from C++17, someday.
14*635a8641SAndroid Build Coastguard Worker template <class T>
ClampToRange(const T & value,const T & min,const T & max)15*635a8641SAndroid Build Coastguard Worker constexpr const T& ClampToRange(const T& value, const T& min, const T& max) {
16*635a8641SAndroid Build Coastguard Worker   return std::min(std::max(value, min), max);
17*635a8641SAndroid Build Coastguard Worker }
18*635a8641SAndroid Build Coastguard Worker 
19*635a8641SAndroid Build Coastguard Worker template <typename T>
IsApproximatelyEqual(T lhs,T rhs,T tolerance)20*635a8641SAndroid Build Coastguard Worker constexpr bool IsApproximatelyEqual(T lhs, T rhs, T tolerance) {
21*635a8641SAndroid Build Coastguard Worker   static_assert(std::is_arithmetic<T>::value, "Argument must be arithmetic");
22*635a8641SAndroid Build Coastguard Worker   return std::abs(rhs - lhs) <= tolerance;
23*635a8641SAndroid Build Coastguard Worker }
24*635a8641SAndroid Build Coastguard Worker 
25*635a8641SAndroid Build Coastguard Worker }  // namespace base
26*635a8641SAndroid Build Coastguard Worker 
27*635a8641SAndroid Build Coastguard Worker #endif  // BASE_NUMERICS_RANGES_H_
28