1 /*
2 * Copyright 2005 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #ifndef RTC_BASE_NUMERICS_MATH_UTILS_H_
12 #define RTC_BASE_NUMERICS_MATH_UTILS_H_
13
14 #include <limits>
15 #include <type_traits>
16
17 #include "rtc_base/checks.h"
18
19 // Given two numbers |x| and |y| such that x >= y, computes the difference
20 // x - y without causing undefined behavior due to signed overflow.
21 template <typename T>
unsigned_difference(T x,T y)22 typename std::make_unsigned<T>::type unsigned_difference(T x, T y) {
23 static_assert(
24 std::is_signed<T>::value,
25 "Function unsigned_difference is only meaningful for signed types.");
26 RTC_DCHECK_GE(x, y);
27 typedef typename std::make_unsigned<T>::type unsigned_type;
28 // int -> unsigned conversion repeatedly adds UINT_MAX + 1 until the number
29 // can be represented as an unsigned. Since we know that the actual
30 // difference x - y can be represented as an unsigned, it is sufficient to
31 // compute the difference modulo UINT_MAX + 1, i.e using unsigned arithmetic.
32 return static_cast<unsigned_type>(x) - static_cast<unsigned_type>(y);
33 }
34
35 // Provide neutral element with respect to min().
36 // Typically used as an initial value for running minimum.
37 template <typename T,
38 typename std::enable_if<std::numeric_limits<T>::has_infinity>::type* =
39 nullptr>
infinity_or_max()40 constexpr T infinity_or_max() {
41 return std::numeric_limits<T>::infinity();
42 }
43
44 template <typename T,
45 typename std::enable_if<
46 !std::numeric_limits<T>::has_infinity>::type* = nullptr>
infinity_or_max()47 constexpr T infinity_or_max() {
48 // Fallback to max().
49 return std::numeric_limits<T>::max();
50 }
51
52 // Provide neutral element with respect to max().
53 // Typically used as an initial value for running maximum.
54 template <typename T,
55 typename std::enable_if<std::numeric_limits<T>::has_infinity>::type* =
56 nullptr>
minus_infinity_or_min()57 constexpr T minus_infinity_or_min() {
58 static_assert(std::is_signed<T>::value, "Unsupported. Please open a bug.");
59 return -std::numeric_limits<T>::infinity();
60 }
61
62 template <typename T,
63 typename std::enable_if<
64 !std::numeric_limits<T>::has_infinity>::type* = nullptr>
minus_infinity_or_min()65 constexpr T minus_infinity_or_min() {
66 // Fallback to min().
67 return std::numeric_limits<T>::min();
68 }
69
70 #endif // RTC_BASE_NUMERICS_MATH_UTILS_H_
71