safe_minmax.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. * Copyright 2017 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. // Minimum and maximum
  11. // ===================
  12. //
  13. // rtc::SafeMin(x, y)
  14. // rtc::SafeMax(x, y)
  15. //
  16. // (These are both constexpr.)
  17. //
  18. // Accept two arguments of either any two integral or any two floating-point
  19. // types, and return the smaller and larger value, respectively, with no
  20. // truncation or wrap-around. If only one of the input types is statically
  21. // guaranteed to be able to represent the result, the return type is that type;
  22. // if either one would do, the result type is the smaller type. (One of these
  23. // two cases always applies.)
  24. //
  25. // * The case with one floating-point and one integral type is not allowed,
  26. // because the floating-point type will have greater range, but may not
  27. // have sufficient precision to represent the integer value exactly.)
  28. //
  29. // Clamp (a.k.a. constrain to a given interval)
  30. // ============================================
  31. //
  32. // rtc::SafeClamp(x, a, b)
  33. //
  34. // Accepts three arguments of any mix of integral types or any mix of
  35. // floating-point types, and returns the value in the closed interval [a, b]
  36. // that is closest to x (that is, if x < a it returns a; if x > b it returns b;
  37. // and if a <= x <= b it returns x). As for SafeMin() and SafeMax(), there is
  38. // no truncation or wrap-around. The result type
  39. //
  40. // 1. is statically guaranteed to be able to represent the result;
  41. //
  42. // 2. is no larger than the largest of the three argument types; and
  43. //
  44. // 3. has the same signedness as the type of the first argument, if this is
  45. // possible without violating the First or Second Law.
  46. //
  47. // There is always at least one type that meets criteria 1 and 2. If more than
  48. // one type meets these criteria equally well, the result type is one of the
  49. // types that is smallest. Note that unlike SafeMin() and SafeMax(),
  50. // SafeClamp() will sometimes pick a return type that isn't the type of any of
  51. // its arguments.
  52. //
  53. // * In this context, a type A is smaller than a type B if it has a smaller
  54. // range; that is, if A::max() - A::min() < B::max() - B::min(). For
  55. // example, int8_t < int16_t == uint16_t < int32_t, and all integral types
  56. // are smaller than all floating-point types.)
  57. //
  58. // * As for SafeMin and SafeMax, mixing integer and floating-point arguments
  59. // is not allowed, because floating-point types have greater range than
  60. // integer types, but do not have sufficient precision to represent the
  61. // values of most integer types exactly.
  62. //
  63. // Requesting a specific return type
  64. // =================================
  65. //
  66. // All three functions allow callers to explicitly specify the return type as a
  67. // template parameter, overriding the default return type. E.g.
  68. //
  69. // rtc::SafeMin<int>(x, y) // returns an int
  70. //
  71. // If the requested type is statically guaranteed to be able to represent the
  72. // result, then everything's fine, and the return type is as requested. But if
  73. // the requested type is too small, a static_assert is triggered.
  74. #ifndef RTC_BASE_NUMERICS_SAFE_MINMAX_H_
  75. #define RTC_BASE_NUMERICS_SAFE_MINMAX_H_
  76. #include <limits>
  77. #include <type_traits>
  78. #include "rtc_base/checks.h"
  79. #include "rtc_base/numerics/safe_compare.h"
  80. #include "rtc_base/type_traits.h"
  81. namespace rtc {
  82. namespace safe_minmax_impl {
  83. // Make the range of a type available via something other than a constexpr
  84. // function, to work around MSVC limitations. See
  85. // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/
  86. template <typename T>
  87. struct Limits {
  88. static constexpr T lowest = std::numeric_limits<T>::lowest();
  89. static constexpr T max = std::numeric_limits<T>::max();
  90. };
  91. template <typename T, bool is_enum = std::is_enum<T>::value>
  92. struct UnderlyingType;
  93. template <typename T>
  94. struct UnderlyingType<T, false> {
  95. using type = T;
  96. };
  97. template <typename T>
  98. struct UnderlyingType<T, true> {
  99. using type = typename std::underlying_type<T>::type;
  100. };
  101. // Given two types T1 and T2, find types that can hold the smallest (in
  102. // ::min_t) and the largest (in ::max_t) of the two values.
  103. template <typename T1,
  104. typename T2,
  105. bool int1 = IsIntlike<T1>::value,
  106. bool int2 = IsIntlike<T2>::value>
  107. struct MType {
  108. static_assert(int1 == int2,
  109. "You may not mix integral and floating-point arguments");
  110. };
  111. // Specialization for when neither type is integral (and therefore presumably
  112. // floating-point).
  113. template <typename T1, typename T2>
  114. struct MType<T1, T2, false, false> {
  115. using min_t = typename std::common_type<T1, T2>::type;
  116. static_assert(std::is_same<min_t, T1>::value ||
  117. std::is_same<min_t, T2>::value,
  118. "");
  119. using max_t = typename std::common_type<T1, T2>::type;
  120. static_assert(std::is_same<max_t, T1>::value ||
  121. std::is_same<max_t, T2>::value,
  122. "");
  123. };
  124. // Specialization for when both types are integral.
  125. template <typename T1, typename T2>
  126. struct MType<T1, T2, true, true> {
  127. // The type with the lowest minimum value. In case of a tie, the type with
  128. // the lowest maximum value. In case that too is a tie, the types have the
  129. // same range, and we arbitrarily pick T1.
  130. using min_t = typename std::conditional<
  131. SafeLt(Limits<T1>::lowest, Limits<T2>::lowest),
  132. T1,
  133. typename std::conditional<
  134. SafeGt(Limits<T1>::lowest, Limits<T2>::lowest),
  135. T2,
  136. typename std::conditional<SafeLe(Limits<T1>::max, Limits<T2>::max),
  137. T1,
  138. T2>::type>::type>::type;
  139. static_assert(std::is_same<min_t, T1>::value ||
  140. std::is_same<min_t, T2>::value,
  141. "");
  142. // The type with the highest maximum value. In case of a tie, the types have
  143. // the same range (because in C++, integer types with the same maximum also
  144. // have the same minimum).
  145. static_assert(SafeNe(Limits<T1>::max, Limits<T2>::max) ||
  146. SafeEq(Limits<T1>::lowest, Limits<T2>::lowest),
  147. "integer types with the same max should have the same min");
  148. using max_t = typename std::
  149. conditional<SafeGe(Limits<T1>::max, Limits<T2>::max), T1, T2>::type;
  150. static_assert(std::is_same<max_t, T1>::value ||
  151. std::is_same<max_t, T2>::value,
  152. "");
  153. };
  154. // A dummy type that we pass around at compile time but never actually use.
  155. // Declared but not defined.
  156. struct DefaultType;
  157. // ::type is A, except we fall back to B if A is DefaultType. We static_assert
  158. // that the chosen type can hold all values that B can hold.
  159. template <typename A, typename B>
  160. struct TypeOr {
  161. using type = typename std::
  162. conditional<std::is_same<A, DefaultType>::value, B, A>::type;
  163. static_assert(SafeLe(Limits<type>::lowest, Limits<B>::lowest) &&
  164. SafeGe(Limits<type>::max, Limits<B>::max),
  165. "The specified type isn't large enough");
  166. static_assert(IsIntlike<type>::value == IsIntlike<B>::value &&
  167. std::is_floating_point<type>::value ==
  168. std::is_floating_point<type>::value,
  169. "float<->int conversions not allowed");
  170. };
  171. } // namespace safe_minmax_impl
  172. template <
  173. typename R = safe_minmax_impl::DefaultType,
  174. typename T1 = safe_minmax_impl::DefaultType,
  175. typename T2 = safe_minmax_impl::DefaultType,
  176. typename R2 = typename safe_minmax_impl::TypeOr<
  177. R,
  178. typename safe_minmax_impl::MType<
  179. typename safe_minmax_impl::UnderlyingType<T1>::type,
  180. typename safe_minmax_impl::UnderlyingType<T2>::type>::min_t>::type>
  181. constexpr R2 SafeMin(T1 a, T2 b) {
  182. static_assert(IsIntlike<T1>::value || std::is_floating_point<T1>::value,
  183. "The first argument must be integral or floating-point");
  184. static_assert(IsIntlike<T2>::value || std::is_floating_point<T2>::value,
  185. "The second argument must be integral or floating-point");
  186. return SafeLt(a, b) ? static_cast<R2>(a) : static_cast<R2>(b);
  187. }
  188. template <
  189. typename R = safe_minmax_impl::DefaultType,
  190. typename T1 = safe_minmax_impl::DefaultType,
  191. typename T2 = safe_minmax_impl::DefaultType,
  192. typename R2 = typename safe_minmax_impl::TypeOr<
  193. R,
  194. typename safe_minmax_impl::MType<
  195. typename safe_minmax_impl::UnderlyingType<T1>::type,
  196. typename safe_minmax_impl::UnderlyingType<T2>::type>::max_t>::type>
  197. constexpr R2 SafeMax(T1 a, T2 b) {
  198. static_assert(IsIntlike<T1>::value || std::is_floating_point<T1>::value,
  199. "The first argument must be integral or floating-point");
  200. static_assert(IsIntlike<T2>::value || std::is_floating_point<T2>::value,
  201. "The second argument must be integral or floating-point");
  202. return SafeGt(a, b) ? static_cast<R2>(a) : static_cast<R2>(b);
  203. }
  204. namespace safe_minmax_impl {
  205. // Given three types T, L, and H, let ::type be a suitable return value for
  206. // SafeClamp(T, L, H). See the docs at the top of this file for details.
  207. template <typename T,
  208. typename L,
  209. typename H,
  210. bool int1 = IsIntlike<T>::value,
  211. bool int2 = IsIntlike<L>::value,
  212. bool int3 = IsIntlike<H>::value>
  213. struct ClampType {
  214. static_assert(int1 == int2 && int1 == int3,
  215. "You may not mix integral and floating-point arguments");
  216. };
  217. // Specialization for when all three types are floating-point.
  218. template <typename T, typename L, typename H>
  219. struct ClampType<T, L, H, false, false, false> {
  220. using type = typename std::common_type<T, L, H>::type;
  221. };
  222. // Specialization for when all three types are integral.
  223. template <typename T, typename L, typename H>
  224. struct ClampType<T, L, H, true, true, true> {
  225. private:
  226. // Range of the return value. The return type must be able to represent this
  227. // full range.
  228. static constexpr auto r_min =
  229. SafeMax(Limits<L>::lowest, SafeMin(Limits<H>::lowest, Limits<T>::lowest));
  230. static constexpr auto r_max =
  231. SafeMin(Limits<H>::max, SafeMax(Limits<L>::max, Limits<T>::max));
  232. // Is the given type an acceptable return type? (That is, can it represent
  233. // all possible return values, and is it no larger than the largest of the
  234. // input types?)
  235. template <typename A>
  236. struct AcceptableType {
  237. private:
  238. static constexpr bool not_too_large = sizeof(A) <= sizeof(L) ||
  239. sizeof(A) <= sizeof(H) ||
  240. sizeof(A) <= sizeof(T);
  241. static constexpr bool range_contained =
  242. SafeLe(Limits<A>::lowest, r_min) && SafeLe(r_max, Limits<A>::max);
  243. public:
  244. static constexpr bool value = not_too_large && range_contained;
  245. };
  246. using best_signed_type = typename std::conditional<
  247. AcceptableType<int8_t>::value,
  248. int8_t,
  249. typename std::conditional<
  250. AcceptableType<int16_t>::value,
  251. int16_t,
  252. typename std::conditional<AcceptableType<int32_t>::value,
  253. int32_t,
  254. int64_t>::type>::type>::type;
  255. using best_unsigned_type = typename std::conditional<
  256. AcceptableType<uint8_t>::value,
  257. uint8_t,
  258. typename std::conditional<
  259. AcceptableType<uint16_t>::value,
  260. uint16_t,
  261. typename std::conditional<AcceptableType<uint32_t>::value,
  262. uint32_t,
  263. uint64_t>::type>::type>::type;
  264. public:
  265. // Pick the best type, preferring the same signedness as T but falling back
  266. // to the other one if necessary.
  267. using type = typename std::conditional<
  268. std::is_signed<T>::value,
  269. typename std::conditional<AcceptableType<best_signed_type>::value,
  270. best_signed_type,
  271. best_unsigned_type>::type,
  272. typename std::conditional<AcceptableType<best_unsigned_type>::value,
  273. best_unsigned_type,
  274. best_signed_type>::type>::type;
  275. static_assert(AcceptableType<type>::value, "");
  276. };
  277. } // namespace safe_minmax_impl
  278. template <
  279. typename R = safe_minmax_impl::DefaultType,
  280. typename T = safe_minmax_impl::DefaultType,
  281. typename L = safe_minmax_impl::DefaultType,
  282. typename H = safe_minmax_impl::DefaultType,
  283. typename R2 = typename safe_minmax_impl::TypeOr<
  284. R,
  285. typename safe_minmax_impl::ClampType<
  286. typename safe_minmax_impl::UnderlyingType<T>::type,
  287. typename safe_minmax_impl::UnderlyingType<L>::type,
  288. typename safe_minmax_impl::UnderlyingType<H>::type>::type>::type>
  289. R2 SafeClamp(T x, L min, H max) {
  290. static_assert(IsIntlike<H>::value || std::is_floating_point<H>::value,
  291. "The first argument must be integral or floating-point");
  292. static_assert(IsIntlike<T>::value || std::is_floating_point<T>::value,
  293. "The second argument must be integral or floating-point");
  294. static_assert(IsIntlike<L>::value || std::is_floating_point<L>::value,
  295. "The third argument must be integral or floating-point");
  296. RTC_DCHECK_LE(min, max);
  297. return SafeLe(x, min)
  298. ? static_cast<R2>(min)
  299. : SafeGe(x, max) ? static_cast<R2>(max) : static_cast<R2>(x);
  300. }
  301. } // namespace rtc
  302. #endif // RTC_BASE_NUMERICS_SAFE_MINMAX_H_