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