1 // Copyright 2013 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
5 #include <stddef.h>
6 #include <stdint.h>
7
8 #include <limits>
9 #include <type_traits>
10
11 #include "base/compiler_specific.h"
12
13 // WARNING: This block must come before the base/numerics headers are included.
14 // These tests deliberately cause arithmetic boundary errors. If the compiler is
15 // aggressive enough, it can const detect these errors, so we disable warnings.
16 #if defined(OS_WIN)
17 #pragma warning(disable : 4756) // Arithmetic overflow.
18 #pragma warning(disable : 4293) // Invalid shift.
19 #endif
20
21 // This may not need to come before the base/numerics headers, but let's keep
22 // it close to the MSVC equivalent.
23 #if defined(__clang__)
24 #pragma clang diagnostic push
25 #pragma clang diagnostic ignored "-Winteger-overflow"
26 #endif
27
28 #include "base/logging.h"
29 #include "base/numerics/safe_conversions.h"
30 #include "base/numerics/safe_math.h"
31 #include "base/test/gtest_util.h"
32 #include "build/build_config.h"
33 #include "testing/gtest/include/gtest/gtest.h"
34
35 #if defined(COMPILER_MSVC) && defined(ARCH_CPU_32_BITS)
36 #include <mmintrin.h>
37 #endif
38
39 namespace base {
40 namespace internal {
41
42 using std::numeric_limits;
43
44 // This is a helper function for finding the maximum value in Src that can be
45 // wholy represented as the destination floating-point type.
46 template <typename Dst, typename Src>
GetMaxConvertibleToFloat()47 Dst GetMaxConvertibleToFloat() {
48 using DstLimits = numeric_limits<Dst>;
49 using SrcLimits = numeric_limits<Src>;
50 static_assert(SrcLimits::is_specialized, "Source must be numeric.");
51 static_assert(DstLimits::is_specialized, "Destination must be numeric.");
52 CHECK(DstLimits::is_iec559);
53
54 if (SrcLimits::digits <= DstLimits::digits &&
55 MaxExponent<Src>::value <= MaxExponent<Dst>::value)
56 return SrcLimits::max();
57 Src max = SrcLimits::max() / 2 + (SrcLimits::is_integer ? 1 : 0);
58 while (max != static_cast<Src>(static_cast<Dst>(max))) {
59 max /= 2;
60 }
61 return static_cast<Dst>(max);
62 }
63
64 // Test corner case promotions used
65 static_assert(IsIntegerArithmeticSafe<int32_t, int8_t, int8_t>::value, "");
66 static_assert(IsIntegerArithmeticSafe<int32_t, int16_t, int8_t>::value, "");
67 static_assert(IsIntegerArithmeticSafe<int32_t, int8_t, int16_t>::value, "");
68 static_assert(!IsIntegerArithmeticSafe<int32_t, int32_t, int8_t>::value, "");
69 static_assert(BigEnoughPromotion<int16_t, int8_t>::is_contained, "");
70 static_assert(BigEnoughPromotion<int32_t, uint32_t>::is_contained, "");
71 static_assert(BigEnoughPromotion<intmax_t, int8_t>::is_contained, "");
72 static_assert(!BigEnoughPromotion<uintmax_t, int8_t>::is_contained, "");
73 static_assert(
74 std::is_same<BigEnoughPromotion<int16_t, int8_t>::type, int16_t>::value,
75 "");
76 static_assert(
77 std::is_same<BigEnoughPromotion<int32_t, uint32_t>::type, int64_t>::value,
78 "");
79 static_assert(
80 std::is_same<BigEnoughPromotion<intmax_t, int8_t>::type, intmax_t>::value,
81 "");
82 static_assert(
83 std::is_same<BigEnoughPromotion<uintmax_t, int8_t>::type, uintmax_t>::value,
84 "");
85 static_assert(BigEnoughPromotion<int16_t, int8_t>::is_contained, "");
86 static_assert(BigEnoughPromotion<int32_t, uint32_t>::is_contained, "");
87 static_assert(BigEnoughPromotion<intmax_t, int8_t>::is_contained, "");
88 static_assert(!BigEnoughPromotion<uintmax_t, int8_t>::is_contained, "");
89 static_assert(
90 std::is_same<FastIntegerArithmeticPromotion<int16_t, int8_t>::type,
91 int32_t>::value,
92 "");
93 static_assert(
94 std::is_same<FastIntegerArithmeticPromotion<int32_t, uint32_t>::type,
95 int64_t>::value,
96 "");
97 static_assert(
98 std::is_same<FastIntegerArithmeticPromotion<intmax_t, int8_t>::type,
99 intmax_t>::value,
100 "");
101 static_assert(
102 std::is_same<FastIntegerArithmeticPromotion<uintmax_t, int8_t>::type,
103 uintmax_t>::value,
104 "");
105 static_assert(FastIntegerArithmeticPromotion<int16_t, int8_t>::is_contained,
106 "");
107 static_assert(FastIntegerArithmeticPromotion<int32_t, uint32_t>::is_contained,
108 "");
109 static_assert(!FastIntegerArithmeticPromotion<intmax_t, int8_t>::is_contained,
110 "");
111 static_assert(!FastIntegerArithmeticPromotion<uintmax_t, int8_t>::is_contained,
112 "");
113
114 template <typename U>
GetNumericValueForTest(const CheckedNumeric<U> & src)115 U GetNumericValueForTest(const CheckedNumeric<U>& src) {
116 return src.state_.value();
117 }
118
119 template <typename U>
GetNumericValueForTest(const ClampedNumeric<U> & src)120 U GetNumericValueForTest(const ClampedNumeric<U>& src) {
121 return static_cast<U>(src);
122 }
123
124 template <typename U>
GetNumericValueForTest(const U & src)125 U GetNumericValueForTest(const U& src) {
126 return src;
127 }
128
129 // Logs the ValueOrDie() failure instead of crashing.
130 struct LogOnFailure {
131 template <typename T>
HandleFailurebase::internal::LogOnFailure132 static T HandleFailure() {
133 LOG(WARNING) << "ValueOrDie() failed unexpectedly.";
134 return T();
135 }
136 };
137
138 template <typename T>
GetValue(const T & src)139 constexpr T GetValue(const T& src) {
140 return src;
141 }
142
143 template <typename T, typename U>
GetValueAsDest(const U & src)144 constexpr T GetValueAsDest(const U& src) {
145 return static_cast<T>(src);
146 }
147
148 template <typename T>
GetValue(const CheckedNumeric<T> & src)149 constexpr T GetValue(const CheckedNumeric<T>& src) {
150 return src.template ValueOrDie<T, LogOnFailure>();
151 }
152
153 template <typename T, typename U>
GetValueAsDest(const CheckedNumeric<U> & src)154 constexpr T GetValueAsDest(const CheckedNumeric<U>& src) {
155 return src.template ValueOrDie<T, LogOnFailure>();
156 }
157
158 template <typename T>
GetValue(const ClampedNumeric<T> & src)159 constexpr T GetValue(const ClampedNumeric<T>& src) {
160 return static_cast<T>(src);
161 }
162
163 template <typename T, typename U>
GetValueAsDest(const ClampedNumeric<U> & src)164 constexpr T GetValueAsDest(const ClampedNumeric<U>& src) {
165 return static_cast<T>(src);
166 }
167
168 // Helper macros to wrap displaying the conversion types and line numbers.
169 #define TEST_EXPECTED_VALIDITY(expected, actual) \
170 EXPECT_EQ(expected, (actual).template Cast<Dst>().IsValid()) \
171 << "Result test: Value " << GetNumericValueForTest(actual) << " as " \
172 << dst << " on line " << line
173
174 #define TEST_EXPECTED_SUCCESS(actual) TEST_EXPECTED_VALIDITY(true, actual)
175 #define TEST_EXPECTED_FAILURE(actual) TEST_EXPECTED_VALIDITY(false, actual)
176
177 // We have to handle promotions, so infer the underlying type below from actual.
178 #define TEST_EXPECTED_VALUE(expected, actual) \
179 EXPECT_EQ(GetValue(expected), GetValueAsDest<decltype(expected)>(actual)) \
180 << "Result test: Value " << GetNumericValueForTest(actual) << " as " \
181 << dst << " on line " << line
182
183 // Test the simple pointer arithmetic overrides.
184 template <typename Dst>
TestStrictPointerMath()185 void TestStrictPointerMath() {
186 Dst dummy_value = 0;
187 Dst* dummy_ptr = &dummy_value;
188 static const Dst kDummyOffset = 2; // Don't want to go too far.
189 EXPECT_EQ(dummy_ptr + kDummyOffset,
190 dummy_ptr + StrictNumeric<Dst>(kDummyOffset));
191 EXPECT_EQ(dummy_ptr - kDummyOffset,
192 dummy_ptr - StrictNumeric<Dst>(kDummyOffset));
193 EXPECT_NE(dummy_ptr, dummy_ptr + StrictNumeric<Dst>(kDummyOffset));
194 EXPECT_NE(dummy_ptr, dummy_ptr - StrictNumeric<Dst>(kDummyOffset));
195 EXPECT_DEATH_IF_SUPPORTED(
196 dummy_ptr + StrictNumeric<size_t>(std::numeric_limits<size_t>::max()),
197 "");
198 }
199
200 // Signed integer arithmetic.
201 template <typename Dst>
TestSpecializedArithmetic(const char * dst,int line,typename std::enable_if<numeric_limits<Dst>::is_integer && numeric_limits<Dst>::is_signed,int>::type=0)202 static void TestSpecializedArithmetic(
203 const char* dst,
204 int line,
205 typename std::enable_if<numeric_limits<Dst>::is_integer &&
206 numeric_limits<Dst>::is_signed,
207 int>::type = 0) {
208 using DstLimits = SaturationDefaultLimits<Dst>;
209 TEST_EXPECTED_FAILURE(-CheckedNumeric<Dst>(DstLimits::lowest()));
210 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()).Abs());
211 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(-1).Abs());
212 TEST_EXPECTED_VALUE(DstLimits::max(),
213 MakeCheckedNum(-DstLimits::max()).Abs());
214
215 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
216 -ClampedNumeric<Dst>(DstLimits::lowest()));
217 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
218 ClampedNumeric<Dst>(DstLimits::lowest()).Abs());
219 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(-1).Abs());
220 TEST_EXPECTED_VALUE(DstLimits::max(),
221 MakeClampedNum(-DstLimits::max()).Abs());
222
223 TEST_EXPECTED_SUCCESS(CheckedNumeric<Dst>(DstLimits::max()) + -1);
224 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) + -1);
225 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) +
226 DstLimits::lowest());
227
228 TEST_EXPECTED_VALUE(DstLimits::max() - 1,
229 ClampedNumeric<Dst>(DstLimits::max()) + -1);
230 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
231 ClampedNumeric<Dst>(DstLimits::lowest()) + -1);
232 TEST_EXPECTED_VALUE(
233 DstLimits::Underflow(),
234 ClampedNumeric<Dst>(DstLimits::lowest()) + DstLimits::lowest());
235
236 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) - 1);
237 TEST_EXPECTED_SUCCESS(CheckedNumeric<Dst>(DstLimits::lowest()) - -1);
238 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::max()) -
239 DstLimits::lowest());
240 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) -
241 DstLimits::max());
242
243 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
244 ClampedNumeric<Dst>(DstLimits::lowest()) - 1);
245 TEST_EXPECTED_VALUE(DstLimits::lowest() + 1,
246 ClampedNumeric<Dst>(DstLimits::lowest()) - -1);
247 TEST_EXPECTED_VALUE(
248 DstLimits::Overflow(),
249 ClampedNumeric<Dst>(DstLimits::max()) - DstLimits::lowest());
250 TEST_EXPECTED_VALUE(
251 DstLimits::Underflow(),
252 ClampedNumeric<Dst>(DstLimits::lowest()) - DstLimits::max());
253
254 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) * 2);
255 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
256 ClampedNumeric<Dst>(DstLimits::lowest()) * 2);
257
258 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) / -1);
259 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(-1) / 2);
260 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) * -1);
261 TEST_EXPECTED_VALUE(DstLimits::max(),
262 CheckedNumeric<Dst>(DstLimits::lowest() + 1) * Dst(-1));
263 TEST_EXPECTED_VALUE(DstLimits::max(),
264 CheckedNumeric<Dst>(-1) * Dst(DstLimits::lowest() + 1));
265 TEST_EXPECTED_VALUE(DstLimits::lowest(),
266 CheckedNumeric<Dst>(DstLimits::lowest()) * Dst(1));
267 TEST_EXPECTED_VALUE(DstLimits::lowest(),
268 CheckedNumeric<Dst>(1) * Dst(DstLimits::lowest()));
269 TEST_EXPECTED_VALUE(
270 typename std::make_unsigned<Dst>::type(0) - DstLimits::lowest(),
271 MakeCheckedNum(DstLimits::lowest()).UnsignedAbs());
272 TEST_EXPECTED_VALUE(DstLimits::max(),
273 MakeCheckedNum(DstLimits::max()).UnsignedAbs());
274 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(0).UnsignedAbs());
275 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1).UnsignedAbs());
276 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(-1).UnsignedAbs());
277
278 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
279 ClampedNumeric<Dst>(DstLimits::lowest()) / -1);
280 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(-1) / 2);
281 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
282 ClampedNumeric<Dst>(DstLimits::lowest()) * -1);
283 TEST_EXPECTED_VALUE(DstLimits::max(),
284 ClampedNumeric<Dst>(DstLimits::lowest() + 1) * Dst(-1));
285 TEST_EXPECTED_VALUE(DstLimits::max(),
286 ClampedNumeric<Dst>(-1) * Dst(DstLimits::lowest() + 1));
287 TEST_EXPECTED_VALUE(DstLimits::lowest(),
288 ClampedNumeric<Dst>(DstLimits::lowest()) * Dst(1));
289 TEST_EXPECTED_VALUE(DstLimits::lowest(),
290 ClampedNumeric<Dst>(1) * Dst(DstLimits::lowest()));
291 TEST_EXPECTED_VALUE(
292 typename std::make_unsigned<Dst>::type(0) - DstLimits::lowest(),
293 MakeClampedNum(DstLimits::lowest()).UnsignedAbs());
294 TEST_EXPECTED_VALUE(DstLimits::max(),
295 MakeClampedNum(DstLimits::max()).UnsignedAbs());
296 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(0).UnsignedAbs());
297 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1).UnsignedAbs());
298 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(-1).UnsignedAbs());
299
300 // Modulus is legal only for integers.
301 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>() % 1);
302 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) % 1);
303 TEST_EXPECTED_VALUE(-1, CheckedNumeric<Dst>(-1) % 2);
304 TEST_EXPECTED_VALUE(-1, CheckedNumeric<Dst>(-1) % -2);
305 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(DstLimits::lowest()) % 2);
306 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(DstLimits::max()) % 2);
307 // Test all the different modulus combinations.
308 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) % CheckedNumeric<Dst>(1));
309 TEST_EXPECTED_VALUE(0, 1 % CheckedNumeric<Dst>(1));
310 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) % 1);
311 CheckedNumeric<Dst> checked_dst = 1;
312 TEST_EXPECTED_VALUE(0, checked_dst %= 1);
313 // Test that div by 0 is avoided but returns invalid result.
314 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1) % 0);
315 // Test bit shifts.
316 volatile Dst negative_one = -1;
317 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1) << negative_one);
318 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1)
319 << (IntegerBitsPlusSign<Dst>::value - 1));
320 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(0)
321 << IntegerBitsPlusSign<Dst>::value);
322 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::max()) << 1);
323 TEST_EXPECTED_VALUE(
324 static_cast<Dst>(1) << (IntegerBitsPlusSign<Dst>::value - 2),
325 CheckedNumeric<Dst>(1) << (IntegerBitsPlusSign<Dst>::value - 2));
326 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(0)
327 << (IntegerBitsPlusSign<Dst>::value - 1));
328 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) << 0);
329 TEST_EXPECTED_VALUE(2, CheckedNumeric<Dst>(1) << 1);
330 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1) >>
331 IntegerBitsPlusSign<Dst>::value);
332 TEST_EXPECTED_VALUE(
333 0, CheckedNumeric<Dst>(1) >> (IntegerBitsPlusSign<Dst>::value - 1));
334 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1) >> negative_one);
335
336 // Modulus is legal only for integers.
337 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>() % 1);
338 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) % 1);
339 TEST_EXPECTED_VALUE(-1, ClampedNumeric<Dst>(-1) % 2);
340 TEST_EXPECTED_VALUE(-1, ClampedNumeric<Dst>(-1) % -2);
341 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(DstLimits::lowest()) % 2);
342 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(DstLimits::max()) % 2);
343 // Test all the different modulus combinations.
344 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) % ClampedNumeric<Dst>(1));
345 TEST_EXPECTED_VALUE(0, 1 % ClampedNumeric<Dst>(1));
346 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) % 1);
347 ClampedNumeric<Dst> clamped_dst = 1;
348 TEST_EXPECTED_VALUE(0, clamped_dst %= 1);
349 TEST_EXPECTED_VALUE(Dst(1), ClampedNumeric<Dst>(1) % 0);
350 // Test bit shifts.
351 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
352 ClampedNumeric<Dst>(1)
353 << (IntegerBitsPlusSign<Dst>::value - 1U));
354 TEST_EXPECTED_VALUE(Dst(0), ClampedNumeric<Dst>(0)
355 << (IntegerBitsPlusSign<Dst>::value + 0U));
356 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
357 ClampedNumeric<Dst>(DstLimits::max()) << 1U);
358 TEST_EXPECTED_VALUE(
359 static_cast<Dst>(1) << (IntegerBitsPlusSign<Dst>::value - 2U),
360 ClampedNumeric<Dst>(1) << (IntegerBitsPlusSign<Dst>::value - 2U));
361 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(0)
362 << (IntegerBitsPlusSign<Dst>::value - 1U));
363 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) << 0U);
364 TEST_EXPECTED_VALUE(2, ClampedNumeric<Dst>(1) << 1U);
365 TEST_EXPECTED_VALUE(
366 0, ClampedNumeric<Dst>(1) >> (IntegerBitsPlusSign<Dst>::value + 0U));
367 TEST_EXPECTED_VALUE(
368 0, ClampedNumeric<Dst>(1) >> (IntegerBitsPlusSign<Dst>::value - 1U));
369 TEST_EXPECTED_VALUE(
370 -1, ClampedNumeric<Dst>(-1) >> (IntegerBitsPlusSign<Dst>::value - 1U));
371 TEST_EXPECTED_VALUE(-1, ClampedNumeric<Dst>(DstLimits::lowest()) >>
372 (IntegerBitsPlusSign<Dst>::value - 0U));
373
374 TestStrictPointerMath<Dst>();
375 }
376
377 // Unsigned integer arithmetic.
378 template <typename Dst>
TestSpecializedArithmetic(const char * dst,int line,typename std::enable_if<numeric_limits<Dst>::is_integer &&!numeric_limits<Dst>::is_signed,int>::type=0)379 static void TestSpecializedArithmetic(
380 const char* dst,
381 int line,
382 typename std::enable_if<numeric_limits<Dst>::is_integer &&
383 !numeric_limits<Dst>::is_signed,
384 int>::type = 0) {
385 using DstLimits = SaturationDefaultLimits<Dst>;
386 TEST_EXPECTED_SUCCESS(-CheckedNumeric<Dst>(DstLimits::lowest()));
387 TEST_EXPECTED_SUCCESS(CheckedNumeric<Dst>(DstLimits::lowest()).Abs());
388 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) + -1);
389 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) - 1);
390 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(DstLimits::lowest()) * 2);
391 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) / 2);
392 TEST_EXPECTED_SUCCESS(CheckedNumeric<Dst>(DstLimits::lowest()).UnsignedAbs());
393 TEST_EXPECTED_SUCCESS(
394 CheckedNumeric<typename std::make_signed<Dst>::type>(
395 std::numeric_limits<typename std::make_signed<Dst>::type>::lowest())
396 .UnsignedAbs());
397 TEST_EXPECTED_VALUE(DstLimits::lowest(),
398 MakeCheckedNum(DstLimits::lowest()).UnsignedAbs());
399 TEST_EXPECTED_VALUE(DstLimits::max(),
400 MakeCheckedNum(DstLimits::max()).UnsignedAbs());
401 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(0).UnsignedAbs());
402 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1).UnsignedAbs());
403
404 TEST_EXPECTED_VALUE(0, -ClampedNumeric<Dst>(DstLimits::lowest()));
405 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(DstLimits::lowest()).Abs());
406 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
407 ClampedNumeric<Dst>(DstLimits::lowest()) + -1);
408 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
409 ClampedNumeric<Dst>(DstLimits::lowest()) - 1);
410 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(DstLimits::lowest()) * 2);
411 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) / 2);
412 TEST_EXPECTED_VALUE(0,
413 ClampedNumeric<Dst>(DstLimits::lowest()).UnsignedAbs());
414 TEST_EXPECTED_VALUE(
415 as_unsigned(
416 std::numeric_limits<typename std::make_signed<Dst>::type>::lowest()),
417 ClampedNumeric<typename std::make_signed<Dst>::type>(
418 std::numeric_limits<typename std::make_signed<Dst>::type>::lowest())
419 .UnsignedAbs());
420 TEST_EXPECTED_VALUE(DstLimits::lowest(),
421 MakeClampedNum(DstLimits::lowest()).UnsignedAbs());
422 TEST_EXPECTED_VALUE(DstLimits::max(),
423 MakeClampedNum(DstLimits::max()).UnsignedAbs());
424 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(0).UnsignedAbs());
425 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1).UnsignedAbs());
426
427 // Modulus is legal only for integers.
428 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>() % 1);
429 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) % 1);
430 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) % 2);
431 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(DstLimits::lowest()) % 2);
432 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(DstLimits::max()) % 2);
433 // Test all the different modulus combinations.
434 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) % CheckedNumeric<Dst>(1));
435 TEST_EXPECTED_VALUE(0, 1 % CheckedNumeric<Dst>(1));
436 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) % 1);
437 CheckedNumeric<Dst> checked_dst = 1;
438 TEST_EXPECTED_VALUE(0, checked_dst %= 1);
439 // Test that div by 0 is avoided but returns invalid result.
440 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1) % 0);
441 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1)
442 << IntegerBitsPlusSign<Dst>::value);
443 // Test bit shifts.
444 volatile int negative_one = -1;
445 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1) << negative_one);
446 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1)
447 << IntegerBitsPlusSign<Dst>::value);
448 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(0)
449 << IntegerBitsPlusSign<Dst>::value);
450 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::max()) << 1);
451 TEST_EXPECTED_VALUE(
452 static_cast<Dst>(1) << (IntegerBitsPlusSign<Dst>::value - 1),
453 CheckedNumeric<Dst>(1) << (IntegerBitsPlusSign<Dst>::value - 1));
454 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) << 0);
455 TEST_EXPECTED_VALUE(2, CheckedNumeric<Dst>(1) << 1);
456 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1) >>
457 IntegerBitsPlusSign<Dst>::value);
458 TEST_EXPECTED_VALUE(
459 0, CheckedNumeric<Dst>(1) >> (IntegerBitsPlusSign<Dst>::value - 1));
460 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1) >> negative_one);
461 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) & 1);
462 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) & 0);
463 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(0) & 1);
464 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) & 0);
465 TEST_EXPECTED_VALUE(std::numeric_limits<Dst>::max(),
466 MakeCheckedNum(DstLimits::max()) & -1);
467 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) | 1);
468 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) | 0);
469 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(0) | 1);
470 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(0) | 0);
471 TEST_EXPECTED_VALUE(std::numeric_limits<Dst>::max(),
472 CheckedNumeric<Dst>(0) | static_cast<Dst>(-1));
473 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) ^ 1);
474 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) ^ 0);
475 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(0) ^ 1);
476 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(0) ^ 0);
477 TEST_EXPECTED_VALUE(std::numeric_limits<Dst>::max(),
478 CheckedNumeric<Dst>(0) ^ static_cast<Dst>(-1));
479 TEST_EXPECTED_VALUE(DstLimits::max(), ~CheckedNumeric<Dst>(0));
480
481 // Modulus is legal only for integers.
482 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>() % 1);
483 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) % 1);
484 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) % 2);
485 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(DstLimits::lowest()) % 2);
486 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(DstLimits::max()) % 2);
487 // Test all the different modulus combinations.
488 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) % ClampedNumeric<Dst>(1));
489 TEST_EXPECTED_VALUE(0, 1 % ClampedNumeric<Dst>(1));
490 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) % 1);
491 ClampedNumeric<Dst> clamped_dst = 1;
492 TEST_EXPECTED_VALUE(0, clamped_dst %= 1);
493 // Test that div by 0 is avoided but returns invalid result.
494 TEST_EXPECTED_VALUE(Dst(1), ClampedNumeric<Dst>(1) % 0);
495 // Test bit shifts.
496 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
497 ClampedNumeric<Dst>(1)
498 << as_unsigned(IntegerBitsPlusSign<Dst>::value));
499 TEST_EXPECTED_VALUE(Dst(0), ClampedNumeric<Dst>(0) << as_unsigned(
500 IntegerBitsPlusSign<Dst>::value));
501 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
502 ClampedNumeric<Dst>(DstLimits::max()) << 1U);
503 TEST_EXPECTED_VALUE(
504 static_cast<Dst>(1) << (IntegerBitsPlusSign<Dst>::value - 1U),
505 ClampedNumeric<Dst>(1) << (IntegerBitsPlusSign<Dst>::value - 1U));
506 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) << 0U);
507 TEST_EXPECTED_VALUE(2, ClampedNumeric<Dst>(1) << 1U);
508 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) >>
509 as_unsigned(IntegerBitsPlusSign<Dst>::value));
510 TEST_EXPECTED_VALUE(
511 0, ClampedNumeric<Dst>(1) >> (IntegerBitsPlusSign<Dst>::value - 1U));
512 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) & 1);
513 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) & 0);
514 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(0) & 1);
515 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) & 0);
516 TEST_EXPECTED_VALUE(std::numeric_limits<Dst>::max(),
517 MakeClampedNum(DstLimits::max()) & -1);
518 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) | 1);
519 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) | 0);
520 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(0) | 1);
521 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(0) | 0);
522 TEST_EXPECTED_VALUE(std::numeric_limits<Dst>::max(),
523 ClampedNumeric<Dst>(0) | static_cast<Dst>(-1));
524 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) ^ 1);
525 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) ^ 0);
526 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(0) ^ 1);
527 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(0) ^ 0);
528 TEST_EXPECTED_VALUE(std::numeric_limits<Dst>::max(),
529 ClampedNumeric<Dst>(0) ^ static_cast<Dst>(-1));
530 TEST_EXPECTED_VALUE(DstLimits::max(), ~ClampedNumeric<Dst>(0));
531
532 TestStrictPointerMath<Dst>();
533 }
534
535 // Floating point arithmetic.
536 template <typename Dst>
TestSpecializedArithmetic(const char * dst,int line,typename std::enable_if<numeric_limits<Dst>::is_iec559,int>::type=0)537 void TestSpecializedArithmetic(
538 const char* dst,
539 int line,
540 typename std::enable_if<numeric_limits<Dst>::is_iec559, int>::type = 0) {
541 using DstLimits = SaturationDefaultLimits<Dst>;
542 TEST_EXPECTED_SUCCESS(-CheckedNumeric<Dst>(DstLimits::lowest()));
543
544 TEST_EXPECTED_SUCCESS(CheckedNumeric<Dst>(DstLimits::lowest()).Abs());
545 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(-1).Abs());
546
547 TEST_EXPECTED_SUCCESS(CheckedNumeric<Dst>(DstLimits::lowest()) + -1);
548 TEST_EXPECTED_SUCCESS(CheckedNumeric<Dst>(DstLimits::max()) + 1);
549 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) +
550 DstLimits::lowest());
551
552 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::max()) -
553 DstLimits::lowest());
554 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) -
555 DstLimits::max());
556
557 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::lowest()) * 2);
558
559 TEST_EXPECTED_VALUE(-0.5, CheckedNumeric<Dst>(-1.0) / 2);
560
561 TEST_EXPECTED_VALUE(DstLimits::max(),
562 -ClampedNumeric<Dst>(DstLimits::lowest()));
563
564 TEST_EXPECTED_VALUE(DstLimits::max(),
565 ClampedNumeric<Dst>(DstLimits::lowest()).Abs());
566 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(-1).Abs());
567
568 TEST_EXPECTED_VALUE(DstLimits::lowest() - 1,
569 ClampedNumeric<Dst>(DstLimits::lowest()) + -1);
570 TEST_EXPECTED_VALUE(DstLimits::max() + 1,
571 ClampedNumeric<Dst>(DstLimits::max()) + 1);
572 TEST_EXPECTED_VALUE(
573 DstLimits::Underflow(),
574 ClampedNumeric<Dst>(DstLimits::lowest()) + DstLimits::lowest());
575
576 TEST_EXPECTED_VALUE(
577 DstLimits::Overflow(),
578 ClampedNumeric<Dst>(DstLimits::max()) - DstLimits::lowest());
579 TEST_EXPECTED_VALUE(
580 DstLimits::Underflow(),
581 ClampedNumeric<Dst>(DstLimits::lowest()) - DstLimits::max());
582
583 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
584 ClampedNumeric<Dst>(DstLimits::lowest()) * 2);
585
586 TEST_EXPECTED_VALUE(-0.5, ClampedNumeric<Dst>(-1.0) / 2);
587 }
588
589 // Generic arithmetic tests.
590 template <typename Dst>
TestArithmetic(const char * dst,int line)591 static void TestArithmetic(const char* dst, int line) {
592 using DstLimits = SaturationDefaultLimits<Dst>;
593
594 EXPECT_EQ(true, CheckedNumeric<Dst>().IsValid());
595 EXPECT_EQ(false, CheckedNumeric<Dst>(CheckedNumeric<Dst>(DstLimits::max()) *
596 DstLimits::max())
597 .IsValid());
598 EXPECT_EQ(static_cast<Dst>(0), CheckedNumeric<Dst>().ValueOrDie());
599 EXPECT_EQ(static_cast<Dst>(0), CheckedNumeric<Dst>().ValueOrDefault(1));
600 EXPECT_EQ(static_cast<Dst>(1),
601 CheckedNumeric<Dst>(CheckedNumeric<Dst>(DstLimits::max()) *
602 DstLimits::max())
603 .ValueOrDefault(1));
604
605 // Test the operator combinations.
606 TEST_EXPECTED_VALUE(2, CheckedNumeric<Dst>(1) + CheckedNumeric<Dst>(1));
607 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) - CheckedNumeric<Dst>(1));
608 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) * CheckedNumeric<Dst>(1));
609 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) / CheckedNumeric<Dst>(1));
610 TEST_EXPECTED_VALUE(2, 1 + CheckedNumeric<Dst>(1));
611 TEST_EXPECTED_VALUE(0, 1 - CheckedNumeric<Dst>(1));
612 TEST_EXPECTED_VALUE(1, 1 * CheckedNumeric<Dst>(1));
613 TEST_EXPECTED_VALUE(1, 1 / CheckedNumeric<Dst>(1));
614 TEST_EXPECTED_VALUE(2, CheckedNumeric<Dst>(1) + 1);
615 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>(1) - 1);
616 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) * 1);
617 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) / 1);
618 CheckedNumeric<Dst> checked_dst = 1;
619 TEST_EXPECTED_VALUE(2, checked_dst += 1);
620 checked_dst = 1;
621 TEST_EXPECTED_VALUE(0, checked_dst -= 1);
622 checked_dst = 1;
623 TEST_EXPECTED_VALUE(1, checked_dst *= 1);
624 checked_dst = 1;
625 TEST_EXPECTED_VALUE(1, checked_dst /= 1);
626
627 TEST_EXPECTED_VALUE(2, ClampedNumeric<Dst>(1) + ClampedNumeric<Dst>(1));
628 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) - ClampedNumeric<Dst>(1));
629 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) * ClampedNumeric<Dst>(1));
630 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) / ClampedNumeric<Dst>(1));
631 TEST_EXPECTED_VALUE(2, 1 + ClampedNumeric<Dst>(1));
632 TEST_EXPECTED_VALUE(0, 1 - ClampedNumeric<Dst>(1));
633 TEST_EXPECTED_VALUE(1, 1 * ClampedNumeric<Dst>(1));
634 TEST_EXPECTED_VALUE(1, 1 / ClampedNumeric<Dst>(1));
635 TEST_EXPECTED_VALUE(2, ClampedNumeric<Dst>(1) + 1);
636 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(1) - 1);
637 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) * 1);
638 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) / 1);
639 ClampedNumeric<Dst> clamped_dst = 1;
640 TEST_EXPECTED_VALUE(2, clamped_dst += 1);
641 clamped_dst = 1;
642 TEST_EXPECTED_VALUE(0, clamped_dst -= 1);
643 clamped_dst = 1;
644 TEST_EXPECTED_VALUE(1, clamped_dst *= 1);
645 clamped_dst = 1;
646 TEST_EXPECTED_VALUE(1, clamped_dst /= 1);
647
648 // Generic negation.
649 if (DstLimits::is_signed) {
650 TEST_EXPECTED_VALUE(0, -CheckedNumeric<Dst>());
651 TEST_EXPECTED_VALUE(-1, -CheckedNumeric<Dst>(1));
652 TEST_EXPECTED_VALUE(1, -CheckedNumeric<Dst>(-1));
653 TEST_EXPECTED_VALUE(static_cast<Dst>(DstLimits::max() * -1),
654 -CheckedNumeric<Dst>(DstLimits::max()));
655
656 TEST_EXPECTED_VALUE(0, -ClampedNumeric<Dst>());
657 TEST_EXPECTED_VALUE(-1, -ClampedNumeric<Dst>(1));
658 TEST_EXPECTED_VALUE(1, -ClampedNumeric<Dst>(-1));
659 TEST_EXPECTED_VALUE(static_cast<Dst>(DstLimits::max() * -1),
660 -ClampedNumeric<Dst>(DstLimits::max()));
661
662 // The runtime paths for saturated negation differ significantly from what
663 // gets evaluated at compile-time. Making this test volatile forces the
664 // compiler to generate code rather than fold constant expressions.
665 volatile Dst value = Dst(0);
666 TEST_EXPECTED_VALUE(0, -MakeClampedNum(value));
667 value = Dst(1);
668 TEST_EXPECTED_VALUE(-1, -MakeClampedNum(value));
669 value = Dst(2);
670 TEST_EXPECTED_VALUE(-2, -MakeClampedNum(value));
671 value = Dst(-1);
672 TEST_EXPECTED_VALUE(1, -MakeClampedNum(value));
673 value = Dst(-2);
674 TEST_EXPECTED_VALUE(2, -MakeClampedNum(value));
675 value = DstLimits::max();
676 TEST_EXPECTED_VALUE(Dst(DstLimits::max() * -1), -MakeClampedNum(value));
677 value = Dst(-1 * DstLimits::max());
678 TEST_EXPECTED_VALUE(DstLimits::max(), -MakeClampedNum(value));
679 value = DstLimits::lowest();
680 TEST_EXPECTED_VALUE(DstLimits::max(), -MakeClampedNum(value));
681 }
682
683 // Generic absolute value.
684 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>().Abs());
685 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1).Abs());
686 TEST_EXPECTED_VALUE(DstLimits::max(),
687 CheckedNumeric<Dst>(DstLimits::max()).Abs());
688
689 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>().Abs());
690 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1).Abs());
691 TEST_EXPECTED_VALUE(DstLimits::max(),
692 ClampedNumeric<Dst>(DstLimits::max()).Abs());
693
694 // Generic addition.
695 TEST_EXPECTED_VALUE(1, (CheckedNumeric<Dst>() + 1));
696 TEST_EXPECTED_VALUE(2, (CheckedNumeric<Dst>(1) + 1));
697 if (numeric_limits<Dst>::is_signed)
698 TEST_EXPECTED_VALUE(0, (CheckedNumeric<Dst>(-1) + 1));
699 TEST_EXPECTED_SUCCESS(CheckedNumeric<Dst>(DstLimits::lowest()) + 1);
700 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::max()) +
701 DstLimits::max());
702
703 TEST_EXPECTED_VALUE(1, (ClampedNumeric<Dst>() + 1));
704 TEST_EXPECTED_VALUE(2, (ClampedNumeric<Dst>(1) + 1));
705 if (numeric_limits<Dst>::is_signed)
706 TEST_EXPECTED_VALUE(0, (ClampedNumeric<Dst>(-1) + 1));
707 TEST_EXPECTED_VALUE(DstLimits::lowest() + 1,
708 ClampedNumeric<Dst>(DstLimits::lowest()) + 1);
709 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
710 ClampedNumeric<Dst>(DstLimits::max()) + DstLimits::max());
711
712 // Generic subtraction.
713 TEST_EXPECTED_VALUE(0, (CheckedNumeric<Dst>(1) - 1));
714 TEST_EXPECTED_SUCCESS(CheckedNumeric<Dst>(DstLimits::max()) - 1);
715 if (numeric_limits<Dst>::is_signed) {
716 TEST_EXPECTED_VALUE(-1, (CheckedNumeric<Dst>() - 1));
717 TEST_EXPECTED_VALUE(-2, (CheckedNumeric<Dst>(-1) - 1));
718 } else {
719 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::max()) - -1);
720 }
721
722 TEST_EXPECTED_VALUE(0, (ClampedNumeric<Dst>(1) - 1));
723 TEST_EXPECTED_VALUE(DstLimits::max() - 1,
724 ClampedNumeric<Dst>(DstLimits::max()) - 1);
725 if (numeric_limits<Dst>::is_signed) {
726 TEST_EXPECTED_VALUE(-1, (ClampedNumeric<Dst>() - 1));
727 TEST_EXPECTED_VALUE(-2, (ClampedNumeric<Dst>(-1) - 1));
728 } else {
729 TEST_EXPECTED_VALUE(DstLimits::max(),
730 ClampedNumeric<Dst>(DstLimits::max()) - -1);
731 }
732
733 // Generic multiplication.
734 TEST_EXPECTED_VALUE(0, (CheckedNumeric<Dst>() * 1));
735 TEST_EXPECTED_VALUE(1, (CheckedNumeric<Dst>(1) * 1));
736 TEST_EXPECTED_VALUE(0, (CheckedNumeric<Dst>(0) * 0));
737 if (numeric_limits<Dst>::is_signed) {
738 TEST_EXPECTED_VALUE(0, (CheckedNumeric<Dst>(-1) * 0));
739 TEST_EXPECTED_VALUE(0, (CheckedNumeric<Dst>(0) * -1));
740 TEST_EXPECTED_VALUE(-2, (CheckedNumeric<Dst>(-1) * 2));
741 } else {
742 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::max()) * -2);
743 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::max()) *
744 CheckedNumeric<uintmax_t>(-2));
745 }
746 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(DstLimits::max()) *
747 DstLimits::max());
748
749 TEST_EXPECTED_VALUE(0, (ClampedNumeric<Dst>() * 1));
750 TEST_EXPECTED_VALUE(1, (ClampedNumeric<Dst>(1) * 1));
751 TEST_EXPECTED_VALUE(0, (ClampedNumeric<Dst>(0) * 0));
752 if (numeric_limits<Dst>::is_signed) {
753 TEST_EXPECTED_VALUE(0, (ClampedNumeric<Dst>(-1) * 0));
754 TEST_EXPECTED_VALUE(0, (ClampedNumeric<Dst>(0) * -1));
755 TEST_EXPECTED_VALUE(-2, (ClampedNumeric<Dst>(-1) * 2));
756 } else {
757 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
758 ClampedNumeric<Dst>(DstLimits::max()) * -2);
759 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(DstLimits::max()) *
760 ClampedNumeric<uintmax_t>(-2));
761 }
762 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
763 ClampedNumeric<Dst>(DstLimits::max()) * DstLimits::max());
764
765 // Generic division.
766 TEST_EXPECTED_VALUE(0, CheckedNumeric<Dst>() / 1);
767 TEST_EXPECTED_VALUE(1, CheckedNumeric<Dst>(1) / 1);
768 TEST_EXPECTED_VALUE(DstLimits::lowest() / 2,
769 CheckedNumeric<Dst>(DstLimits::lowest()) / 2);
770 TEST_EXPECTED_VALUE(DstLimits::max() / 2,
771 CheckedNumeric<Dst>(DstLimits::max()) / 2);
772 TEST_EXPECTED_FAILURE(CheckedNumeric<Dst>(1) / 0);
773
774 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>() / 1);
775 TEST_EXPECTED_VALUE(1, ClampedNumeric<Dst>(1) / 1);
776 TEST_EXPECTED_VALUE(DstLimits::lowest() / 2,
777 ClampedNumeric<Dst>(DstLimits::lowest()) / 2);
778 TEST_EXPECTED_VALUE(DstLimits::max() / 2,
779 ClampedNumeric<Dst>(DstLimits::max()) / 2);
780 TEST_EXPECTED_VALUE(DstLimits::Overflow(), ClampedNumeric<Dst>(1) / 0);
781 TEST_EXPECTED_VALUE(DstLimits::Underflow(), ClampedNumeric<Dst>(-1) / 0);
782 TEST_EXPECTED_VALUE(0, ClampedNumeric<Dst>(0) / 0);
783
784 TestSpecializedArithmetic<Dst>(dst, line);
785 }
786
787 // Helper macro to wrap displaying the conversion types and line numbers.
788 #define TEST_ARITHMETIC(Dst) TestArithmetic<Dst>(#Dst, __LINE__)
789
TEST(SafeNumerics,SignedIntegerMath)790 TEST(SafeNumerics, SignedIntegerMath) {
791 TEST_ARITHMETIC(int8_t);
792 TEST_ARITHMETIC(int16_t);
793 TEST_ARITHMETIC(int);
794 TEST_ARITHMETIC(intptr_t);
795 TEST_ARITHMETIC(intmax_t);
796 }
797
TEST(SafeNumerics,UnsignedIntegerMath)798 TEST(SafeNumerics, UnsignedIntegerMath) {
799 TEST_ARITHMETIC(uint8_t);
800 TEST_ARITHMETIC(uint16_t);
801 TEST_ARITHMETIC(unsigned int);
802 TEST_ARITHMETIC(uintptr_t);
803 TEST_ARITHMETIC(uintmax_t);
804 }
805
TEST(SafeNumerics,FloatingPointMath)806 TEST(SafeNumerics, FloatingPointMath) {
807 TEST_ARITHMETIC(float);
808 TEST_ARITHMETIC(double);
809 }
810
811 // Enumerates the five different conversions types we need to test.
812 enum NumericConversionType {
813 SIGN_PRESERVING_VALUE_PRESERVING,
814 SIGN_PRESERVING_NARROW,
815 SIGN_TO_UNSIGN_WIDEN_OR_EQUAL,
816 SIGN_TO_UNSIGN_NARROW,
817 UNSIGN_TO_SIGN_NARROW_OR_EQUAL,
818 };
819
820 // Template covering the different conversion tests.
821 template <typename Dst, typename Src, NumericConversionType conversion>
822 struct TestNumericConversion {};
823
824 enum RangeConstraint {
825 RANGE_VALID = 0x0, // Value can be represented by the destination type.
826 RANGE_UNDERFLOW = 0x1, // Value would underflow.
827 RANGE_OVERFLOW = 0x2, // Value would overflow.
828 RANGE_INVALID = RANGE_UNDERFLOW | RANGE_OVERFLOW // Invalid (i.e. NaN).
829 };
830
831 // These are some wrappers to make the tests a bit cleaner.
RangeCheckToEnum(const RangeCheck constraint)832 constexpr RangeConstraint RangeCheckToEnum(const RangeCheck constraint) {
833 return static_cast<RangeConstraint>(
834 static_cast<int>(constraint.IsOverflowFlagSet()) << 1 |
835 static_cast<int>(constraint.IsUnderflowFlagSet()));
836 }
837
838 // EXPECT_EQ wrappers providing specific detail on test failures.
839 #define TEST_EXPECTED_RANGE(expected, actual) \
840 EXPECT_EQ(expected, \
841 RangeCheckToEnum(DstRangeRelationToSrcRange<Dst>(actual))) \
842 << "Conversion test: " << src << " value " << actual << " to " << dst \
843 << " on line " << line
844
845 template <typename Dst, typename Src>
TestStrictComparison(const char * dst,const char * src,int line)846 void TestStrictComparison(const char* dst, const char* src, int line) {
847 using DstLimits = numeric_limits<Dst>;
848 using SrcLimits = numeric_limits<Src>;
849 static_assert(StrictNumeric<Src>(SrcLimits::lowest()) < DstLimits::max(), "");
850 static_assert(StrictNumeric<Src>(SrcLimits::lowest()) < SrcLimits::max(), "");
851 static_assert(!(StrictNumeric<Src>(SrcLimits::lowest()) >= DstLimits::max()),
852 "");
853 static_assert(!(StrictNumeric<Src>(SrcLimits::lowest()) >= SrcLimits::max()),
854 "");
855 static_assert(StrictNumeric<Src>(SrcLimits::lowest()) <= DstLimits::max(),
856 "");
857 static_assert(StrictNumeric<Src>(SrcLimits::lowest()) <= SrcLimits::max(),
858 "");
859 static_assert(!(StrictNumeric<Src>(SrcLimits::lowest()) > DstLimits::max()),
860 "");
861 static_assert(!(StrictNumeric<Src>(SrcLimits::lowest()) > SrcLimits::max()),
862 "");
863 static_assert(StrictNumeric<Src>(SrcLimits::max()) > DstLimits::lowest(), "");
864 static_assert(StrictNumeric<Src>(SrcLimits::max()) > SrcLimits::lowest(), "");
865 static_assert(!(StrictNumeric<Src>(SrcLimits::max()) <= DstLimits::lowest()),
866 "");
867 static_assert(!(StrictNumeric<Src>(SrcLimits::max()) <= SrcLimits::lowest()),
868 "");
869 static_assert(StrictNumeric<Src>(SrcLimits::max()) >= DstLimits::lowest(),
870 "");
871 static_assert(StrictNumeric<Src>(SrcLimits::max()) >= SrcLimits::lowest(),
872 "");
873 static_assert(!(StrictNumeric<Src>(SrcLimits::max()) < DstLimits::lowest()),
874 "");
875 static_assert(!(StrictNumeric<Src>(SrcLimits::max()) < SrcLimits::lowest()),
876 "");
877 static_assert(StrictNumeric<Src>(static_cast<Src>(1)) == static_cast<Dst>(1),
878 "");
879 static_assert(StrictNumeric<Src>(static_cast<Src>(1)) != static_cast<Dst>(0),
880 "");
881 static_assert(StrictNumeric<Src>(SrcLimits::max()) != static_cast<Dst>(0),
882 "");
883 static_assert(StrictNumeric<Src>(SrcLimits::max()) != DstLimits::lowest(),
884 "");
885 static_assert(
886 !(StrictNumeric<Src>(static_cast<Src>(1)) != static_cast<Dst>(1)), "");
887 static_assert(
888 !(StrictNumeric<Src>(static_cast<Src>(1)) == static_cast<Dst>(0)), "");
889
890 // Due to differences in float handling between compilers, these aren't
891 // compile-time constants everywhere. So, we use run-time tests.
892 EXPECT_EQ(
893 SrcLimits::max(),
894 MakeCheckedNum(SrcLimits::max()).Max(DstLimits::lowest()).ValueOrDie());
895 EXPECT_EQ(
896 DstLimits::max(),
897 MakeCheckedNum(SrcLimits::lowest()).Max(DstLimits::max()).ValueOrDie());
898 EXPECT_EQ(
899 DstLimits::lowest(),
900 MakeCheckedNum(SrcLimits::max()).Min(DstLimits::lowest()).ValueOrDie());
901 EXPECT_EQ(
902 SrcLimits::lowest(),
903 MakeCheckedNum(SrcLimits::lowest()).Min(DstLimits::max()).ValueOrDie());
904 EXPECT_EQ(SrcLimits::lowest(), CheckMin(MakeStrictNum(1), MakeCheckedNum(0),
905 DstLimits::max(), SrcLimits::lowest())
906 .ValueOrDie());
907 EXPECT_EQ(DstLimits::max(), CheckMax(MakeStrictNum(1), MakeCheckedNum(0),
908 DstLimits::max(), SrcLimits::lowest())
909 .ValueOrDie());
910
911 EXPECT_EQ(SrcLimits::max(),
912 MakeClampedNum(SrcLimits::max()).Max(DstLimits::lowest()));
913 EXPECT_EQ(DstLimits::max(),
914 MakeClampedNum(SrcLimits::lowest()).Max(DstLimits::max()));
915 EXPECT_EQ(DstLimits::lowest(),
916 MakeClampedNum(SrcLimits::max()).Min(DstLimits::lowest()));
917 EXPECT_EQ(SrcLimits::lowest(),
918 MakeClampedNum(SrcLimits::lowest()).Min(DstLimits::max()));
919 EXPECT_EQ(SrcLimits::lowest(),
920 ClampMin(MakeStrictNum(1), MakeClampedNum(0), DstLimits::max(),
921 SrcLimits::lowest()));
922 EXPECT_EQ(DstLimits::max(), ClampMax(MakeStrictNum(1), MakeClampedNum(0),
923 DstLimits::max(), SrcLimits::lowest()));
924
925 if (IsValueInRangeForNumericType<Dst>(SrcLimits::max())) {
926 TEST_EXPECTED_VALUE(Dst(SrcLimits::max()), (CommonMax<Dst, Src>()));
927 TEST_EXPECTED_VALUE(Dst(SrcLimits::max()),
928 (CommonMaxOrMin<Dst, Src>(false)));
929 } else {
930 TEST_EXPECTED_VALUE(DstLimits::max(), (CommonMax<Dst, Src>()));
931 TEST_EXPECTED_VALUE(DstLimits::max(), (CommonMaxOrMin<Dst, Src>(false)));
932 }
933
934 if (IsValueInRangeForNumericType<Dst>(SrcLimits::lowest())) {
935 TEST_EXPECTED_VALUE(Dst(SrcLimits::lowest()), (CommonMin<Dst, Src>()));
936 TEST_EXPECTED_VALUE(Dst(SrcLimits::lowest()),
937 (CommonMaxOrMin<Dst, Src>(true)));
938 } else {
939 TEST_EXPECTED_VALUE(DstLimits::lowest(), (CommonMin<Dst, Src>()));
940 TEST_EXPECTED_VALUE(DstLimits::lowest(), (CommonMaxOrMin<Dst, Src>(true)));
941 }
942 }
943
944 template <typename Dst, typename Src>
945 struct TestNumericConversion<Dst, Src, SIGN_PRESERVING_VALUE_PRESERVING> {
Testbase::internal::TestNumericConversion946 static void Test(const char* dst, const char* src, int line) {
947 using SrcLimits = SaturationDefaultLimits<Src>;
948 using DstLimits = SaturationDefaultLimits<Dst>;
949 // Integral to floating.
950 static_assert((DstLimits::is_iec559 && SrcLimits::is_integer) ||
951 // Not floating to integral and...
952 (!(DstLimits::is_integer && SrcLimits::is_iec559) &&
953 // Same sign, same numeric, source is narrower or same.
954 ((SrcLimits::is_signed == DstLimits::is_signed &&
955 MaxExponent<Dst>::value >= MaxExponent<Src>::value) ||
956 // Or signed destination and source is smaller
957 (DstLimits::is_signed &&
958 MaxExponent<Dst>::value >= MaxExponent<Src>::value))),
959 "Comparison must be sign preserving and value preserving");
960
961 TestStrictComparison<Dst, Src>(dst, src, line);
962
963 const CheckedNumeric<Dst> checked_dst = SrcLimits::max();
964 const ClampedNumeric<Dst> clamped_dst = SrcLimits::max();
965 TEST_EXPECTED_SUCCESS(checked_dst);
966 TEST_EXPECTED_VALUE(Dst(SrcLimits::max()), clamped_dst);
967 if (MaxExponent<Dst>::value > MaxExponent<Src>::value) {
968 if (MaxExponent<Dst>::value >= MaxExponent<Src>::value * 2 - 1) {
969 // At least twice larger type.
970 TEST_EXPECTED_SUCCESS(SrcLimits::max() * checked_dst);
971 TEST_EXPECTED_VALUE(SrcLimits::max() * clamped_dst,
972 Dst(SrcLimits::max()) * SrcLimits::max());
973 } else { // Larger, but not at least twice as large.
974 TEST_EXPECTED_FAILURE(SrcLimits::max() * checked_dst);
975 TEST_EXPECTED_SUCCESS(checked_dst + 1);
976 TEST_EXPECTED_VALUE(DstLimits::Overflow(),
977 SrcLimits::max() * clamped_dst);
978 TEST_EXPECTED_VALUE(Dst(SrcLimits::max()) + Dst(1),
979 clamped_dst + Dst(1));
980 }
981 } else { // Same width type.
982 TEST_EXPECTED_FAILURE(checked_dst + 1);
983 TEST_EXPECTED_VALUE(DstLimits::Overflow(), clamped_dst + Dst(1));
984 }
985
986 TEST_EXPECTED_RANGE(RANGE_VALID, SrcLimits::max());
987 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(1));
988 if (SrcLimits::is_iec559) {
989 TEST_EXPECTED_RANGE(RANGE_VALID, SrcLimits::max() * static_cast<Src>(-1));
990 TEST_EXPECTED_RANGE(RANGE_OVERFLOW, SrcLimits::infinity());
991 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, SrcLimits::infinity() * -1);
992 TEST_EXPECTED_RANGE(RANGE_INVALID, SrcLimits::quiet_NaN());
993 } else if (numeric_limits<Src>::is_signed) {
994 // This block reverses the Src to Dst relationship so we don't have to
995 // complicate the test macros.
996 if (!std::is_same<Src, Dst>::value) {
997 TEST_EXPECTED_SUCCESS(CheckDiv(SrcLimits::lowest(), Dst(-1)));
998 }
999 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(-1));
1000 TEST_EXPECTED_RANGE(RANGE_VALID, SrcLimits::lowest());
1001 }
1002 }
1003 };
1004
1005 template <typename Dst, typename Src>
1006 struct TestNumericConversion<Dst, Src, SIGN_PRESERVING_NARROW> {
Testbase::internal::TestNumericConversion1007 static void Test(const char* dst, const char* src, int line) {
1008 using SrcLimits = SaturationDefaultLimits<Src>;
1009 using DstLimits = SaturationDefaultLimits<Dst>;
1010 static_assert(SrcLimits::is_signed == DstLimits::is_signed,
1011 "Destination and source sign must be the same");
1012 static_assert(MaxExponent<Dst>::value <= MaxExponent<Src>::value,
1013 "Destination must be narrower than source");
1014
1015 TestStrictComparison<Dst, Src>(dst, src, line);
1016
1017 const CheckedNumeric<Dst> checked_dst;
1018 TEST_EXPECTED_FAILURE(checked_dst + SrcLimits::max());
1019 TEST_EXPECTED_VALUE(1, checked_dst + Src(1));
1020 TEST_EXPECTED_FAILURE(checked_dst - SrcLimits::max());
1021
1022 ClampedNumeric<Dst> clamped_dst;
1023 TEST_EXPECTED_VALUE(DstLimits::Overflow(), clamped_dst + SrcLimits::max());
1024 TEST_EXPECTED_VALUE(1, clamped_dst + Src(1));
1025 TEST_EXPECTED_VALUE(DstLimits::Underflow(), clamped_dst - SrcLimits::max());
1026 clamped_dst += SrcLimits::max();
1027 TEST_EXPECTED_VALUE(DstLimits::Overflow(), clamped_dst);
1028 clamped_dst = DstLimits::max();
1029 clamped_dst += SrcLimits::max();
1030 TEST_EXPECTED_VALUE(DstLimits::Overflow(), clamped_dst);
1031 clamped_dst = DstLimits::max();
1032 clamped_dst -= SrcLimits::max();
1033 TEST_EXPECTED_VALUE(DstLimits::Underflow(), clamped_dst);
1034 clamped_dst = 0;
1035
1036 TEST_EXPECTED_RANGE(RANGE_OVERFLOW, SrcLimits::max());
1037 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(1));
1038 if (SrcLimits::is_iec559) {
1039 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, SrcLimits::max() * -1);
1040 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(-1));
1041 TEST_EXPECTED_RANGE(RANGE_OVERFLOW, SrcLimits::infinity());
1042 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, SrcLimits::infinity() * -1);
1043 TEST_EXPECTED_RANGE(RANGE_INVALID, SrcLimits::quiet_NaN());
1044 if (DstLimits::is_integer) {
1045 if (SrcLimits::digits < DstLimits::digits) {
1046 TEST_EXPECTED_RANGE(RANGE_OVERFLOW,
1047 static_cast<Src>(DstLimits::max()));
1048 } else {
1049 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(DstLimits::max()));
1050 }
1051 TEST_EXPECTED_RANGE(
1052 RANGE_VALID,
1053 static_cast<Src>(GetMaxConvertibleToFloat<Src, Dst>()));
1054 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(DstLimits::lowest()));
1055 }
1056 } else if (SrcLimits::is_signed) {
1057 TEST_EXPECTED_VALUE(-1, checked_dst - static_cast<Src>(1));
1058 TEST_EXPECTED_VALUE(-1, clamped_dst - static_cast<Src>(1));
1059 TEST_EXPECTED_VALUE(Src(Src(0) - DstLimits::lowest()),
1060 ClampDiv(DstLimits::lowest(), Src(-1)));
1061 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, SrcLimits::lowest());
1062 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(-1));
1063 } else {
1064 TEST_EXPECTED_FAILURE(checked_dst - static_cast<Src>(1));
1065 TEST_EXPECTED_VALUE(Dst(0), clamped_dst - static_cast<Src>(1));
1066 TEST_EXPECTED_RANGE(RANGE_VALID, SrcLimits::lowest());
1067 }
1068 }
1069 };
1070
1071 template <typename Dst, typename Src>
1072 struct TestNumericConversion<Dst, Src, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL> {
Testbase::internal::TestNumericConversion1073 static void Test(const char* dst, const char* src, int line) {
1074 using SrcLimits = SaturationDefaultLimits<Src>;
1075 using DstLimits = SaturationDefaultLimits<Dst>;
1076 static_assert(MaxExponent<Dst>::value >= MaxExponent<Src>::value,
1077 "Destination must be equal or wider than source.");
1078 static_assert(SrcLimits::is_signed, "Source must be signed");
1079 static_assert(!DstLimits::is_signed, "Destination must be unsigned");
1080
1081 TestStrictComparison<Dst, Src>(dst, src, line);
1082
1083 const CheckedNumeric<Dst> checked_dst;
1084 TEST_EXPECTED_VALUE(SrcLimits::max(), checked_dst + SrcLimits::max());
1085 TEST_EXPECTED_FAILURE(checked_dst + static_cast<Src>(-1));
1086 TEST_EXPECTED_SUCCESS(checked_dst * static_cast<Src>(-1));
1087 TEST_EXPECTED_FAILURE(checked_dst + SrcLimits::lowest());
1088 TEST_EXPECTED_VALUE(Dst(0), CheckDiv(Dst(0), Src(-1)));
1089
1090 const ClampedNumeric<Dst> clamped_dst;
1091 TEST_EXPECTED_VALUE(SrcLimits::max(), clamped_dst + SrcLimits::max());
1092 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
1093 clamped_dst + static_cast<Src>(-1));
1094 TEST_EXPECTED_VALUE(0, clamped_dst * static_cast<Src>(-1));
1095 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
1096 clamped_dst + SrcLimits::lowest());
1097
1098 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, SrcLimits::lowest());
1099 TEST_EXPECTED_RANGE(RANGE_VALID, SrcLimits::max());
1100 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(1));
1101 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, static_cast<Src>(-1));
1102 }
1103 };
1104
1105 template <typename Dst, typename Src>
1106 struct TestNumericConversion<Dst, Src, SIGN_TO_UNSIGN_NARROW> {
Testbase::internal::TestNumericConversion1107 static void Test(const char* dst, const char* src, int line) {
1108 using SrcLimits = SaturationDefaultLimits<Src>;
1109 using DstLimits = SaturationDefaultLimits<Dst>;
1110 static_assert(MaxExponent<Dst>::value < MaxExponent<Src>::value,
1111 "Destination must be narrower than source.");
1112 static_assert(SrcLimits::is_signed, "Source must be signed.");
1113 static_assert(!DstLimits::is_signed, "Destination must be unsigned.");
1114
1115 TestStrictComparison<Dst, Src>(dst, src, line);
1116
1117 const CheckedNumeric<Dst> checked_dst;
1118 TEST_EXPECTED_VALUE(1, checked_dst + static_cast<Src>(1));
1119 TEST_EXPECTED_FAILURE(checked_dst + SrcLimits::max());
1120 TEST_EXPECTED_FAILURE(checked_dst + static_cast<Src>(-1));
1121 TEST_EXPECTED_FAILURE(checked_dst + SrcLimits::lowest());
1122
1123 ClampedNumeric<Dst> clamped_dst;
1124 TEST_EXPECTED_VALUE(1, clamped_dst + static_cast<Src>(1));
1125 TEST_EXPECTED_VALUE(DstLimits::Overflow(), clamped_dst + SrcLimits::max());
1126 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
1127 clamped_dst + static_cast<Src>(-1));
1128 TEST_EXPECTED_VALUE(DstLimits::Underflow(),
1129 clamped_dst + SrcLimits::lowest());
1130 clamped_dst += SrcLimits::max();
1131 TEST_EXPECTED_VALUE(DstLimits::Overflow(), clamped_dst);
1132 clamped_dst = DstLimits::max();
1133 clamped_dst += SrcLimits::max();
1134 TEST_EXPECTED_VALUE(DstLimits::Overflow(), clamped_dst);
1135 clamped_dst = DstLimits::max();
1136 clamped_dst -= SrcLimits::max();
1137 TEST_EXPECTED_VALUE(DstLimits::Underflow(), clamped_dst);
1138 clamped_dst = 0;
1139
1140 TEST_EXPECTED_RANGE(RANGE_OVERFLOW, SrcLimits::max());
1141 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(1));
1142 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, static_cast<Src>(-1));
1143
1144 // Additional saturation tests.
1145 EXPECT_EQ(DstLimits::max(), saturated_cast<Dst>(SrcLimits::max()));
1146 EXPECT_EQ(DstLimits::lowest(), saturated_cast<Dst>(SrcLimits::lowest()));
1147
1148 if (SrcLimits::is_iec559) {
1149 EXPECT_EQ(Dst(0), saturated_cast<Dst>(SrcLimits::quiet_NaN()));
1150
1151 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, SrcLimits::max() * -1);
1152 TEST_EXPECTED_RANGE(RANGE_OVERFLOW, SrcLimits::infinity());
1153 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, SrcLimits::infinity() * -1);
1154 TEST_EXPECTED_RANGE(RANGE_INVALID, SrcLimits::quiet_NaN());
1155 if (DstLimits::is_integer) {
1156 if (SrcLimits::digits < DstLimits::digits) {
1157 TEST_EXPECTED_RANGE(RANGE_OVERFLOW,
1158 static_cast<Src>(DstLimits::max()));
1159 } else {
1160 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(DstLimits::max()));
1161 }
1162 TEST_EXPECTED_RANGE(
1163 RANGE_VALID,
1164 static_cast<Src>(GetMaxConvertibleToFloat<Src, Dst>()));
1165 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(DstLimits::lowest()));
1166 }
1167 } else {
1168 TEST_EXPECTED_RANGE(RANGE_UNDERFLOW, SrcLimits::lowest());
1169 }
1170 }
1171 };
1172
1173 template <typename Dst, typename Src>
1174 struct TestNumericConversion<Dst, Src, UNSIGN_TO_SIGN_NARROW_OR_EQUAL> {
Testbase::internal::TestNumericConversion1175 static void Test(const char* dst, const char* src, int line) {
1176 using SrcLimits = SaturationDefaultLimits<Src>;
1177 using DstLimits = SaturationDefaultLimits<Dst>;
1178 static_assert(MaxExponent<Dst>::value <= MaxExponent<Src>::value,
1179 "Destination must be narrower or equal to source.");
1180 static_assert(!SrcLimits::is_signed, "Source must be unsigned.");
1181 static_assert(DstLimits::is_signed, "Destination must be signed.");
1182
1183 TestStrictComparison<Dst, Src>(dst, src, line);
1184
1185 const CheckedNumeric<Dst> checked_dst;
1186 TEST_EXPECTED_VALUE(1, checked_dst + static_cast<Src>(1));
1187 TEST_EXPECTED_FAILURE(checked_dst + SrcLimits::max());
1188 TEST_EXPECTED_VALUE(SrcLimits::lowest(), checked_dst + SrcLimits::lowest());
1189
1190 const ClampedNumeric<Dst> clamped_dst;
1191 TEST_EXPECTED_VALUE(1, clamped_dst + static_cast<Src>(1));
1192 TEST_EXPECTED_VALUE(DstLimits::Overflow(), clamped_dst + SrcLimits::max());
1193 TEST_EXPECTED_VALUE(SrcLimits::lowest(), clamped_dst + SrcLimits::lowest());
1194
1195 TEST_EXPECTED_RANGE(RANGE_VALID, SrcLimits::lowest());
1196 TEST_EXPECTED_RANGE(RANGE_OVERFLOW, SrcLimits::max());
1197 TEST_EXPECTED_RANGE(RANGE_VALID, static_cast<Src>(1));
1198
1199 // Additional saturation tests.
1200 EXPECT_EQ(DstLimits::max(), saturated_cast<Dst>(SrcLimits::max()));
1201 EXPECT_EQ(Dst(0), saturated_cast<Dst>(SrcLimits::lowest()));
1202 }
1203 };
1204
1205 // Helper macro to wrap displaying the conversion types and line numbers
1206 #define TEST_NUMERIC_CONVERSION(d, s, t) \
1207 TestNumericConversion<d, s, t>::Test(#d, #s, __LINE__)
1208
TEST(SafeNumerics,IntMinOperations)1209 TEST(SafeNumerics, IntMinOperations) {
1210 TEST_NUMERIC_CONVERSION(int8_t, int8_t, SIGN_PRESERVING_VALUE_PRESERVING);
1211 TEST_NUMERIC_CONVERSION(uint8_t, uint8_t, SIGN_PRESERVING_VALUE_PRESERVING);
1212
1213 TEST_NUMERIC_CONVERSION(int8_t, int16_t, SIGN_PRESERVING_NARROW);
1214 TEST_NUMERIC_CONVERSION(int8_t, int, SIGN_PRESERVING_NARROW);
1215 TEST_NUMERIC_CONVERSION(uint8_t, uint16_t, SIGN_PRESERVING_NARROW);
1216 TEST_NUMERIC_CONVERSION(uint8_t, unsigned int, SIGN_PRESERVING_NARROW);
1217 TEST_NUMERIC_CONVERSION(int8_t, float, SIGN_PRESERVING_NARROW);
1218
1219 TEST_NUMERIC_CONVERSION(uint8_t, int8_t, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
1220
1221 TEST_NUMERIC_CONVERSION(uint8_t, int16_t, SIGN_TO_UNSIGN_NARROW);
1222 TEST_NUMERIC_CONVERSION(uint8_t, int, SIGN_TO_UNSIGN_NARROW);
1223 TEST_NUMERIC_CONVERSION(uint8_t, intmax_t, SIGN_TO_UNSIGN_NARROW);
1224 TEST_NUMERIC_CONVERSION(uint8_t, float, SIGN_TO_UNSIGN_NARROW);
1225
1226 TEST_NUMERIC_CONVERSION(int8_t, uint16_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
1227 TEST_NUMERIC_CONVERSION(int8_t, unsigned int, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
1228 TEST_NUMERIC_CONVERSION(int8_t, uintmax_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
1229 }
1230
TEST(SafeNumerics,Int16Operations)1231 TEST(SafeNumerics, Int16Operations) {
1232 TEST_NUMERIC_CONVERSION(int16_t, int16_t, SIGN_PRESERVING_VALUE_PRESERVING);
1233 TEST_NUMERIC_CONVERSION(uint16_t, uint16_t, SIGN_PRESERVING_VALUE_PRESERVING);
1234
1235 TEST_NUMERIC_CONVERSION(int16_t, int, SIGN_PRESERVING_NARROW);
1236 TEST_NUMERIC_CONVERSION(uint16_t, unsigned int, SIGN_PRESERVING_NARROW);
1237 TEST_NUMERIC_CONVERSION(int16_t, float, SIGN_PRESERVING_NARROW);
1238
1239 TEST_NUMERIC_CONVERSION(uint16_t, int16_t, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
1240
1241 TEST_NUMERIC_CONVERSION(uint16_t, int, SIGN_TO_UNSIGN_NARROW);
1242 TEST_NUMERIC_CONVERSION(uint16_t, intmax_t, SIGN_TO_UNSIGN_NARROW);
1243 TEST_NUMERIC_CONVERSION(uint16_t, float, SIGN_TO_UNSIGN_NARROW);
1244
1245 TEST_NUMERIC_CONVERSION(int16_t, unsigned int,
1246 UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
1247 TEST_NUMERIC_CONVERSION(int16_t, uintmax_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
1248 }
1249
TEST(SafeNumerics,IntOperations)1250 TEST(SafeNumerics, IntOperations) {
1251 TEST_NUMERIC_CONVERSION(int, int, SIGN_PRESERVING_VALUE_PRESERVING);
1252 TEST_NUMERIC_CONVERSION(unsigned int, unsigned int,
1253 SIGN_PRESERVING_VALUE_PRESERVING);
1254 TEST_NUMERIC_CONVERSION(int, int8_t, SIGN_PRESERVING_VALUE_PRESERVING);
1255 TEST_NUMERIC_CONVERSION(unsigned int, uint8_t,
1256 SIGN_PRESERVING_VALUE_PRESERVING);
1257 TEST_NUMERIC_CONVERSION(int, uint8_t, SIGN_PRESERVING_VALUE_PRESERVING);
1258
1259 TEST_NUMERIC_CONVERSION(int, intmax_t, SIGN_PRESERVING_NARROW);
1260 TEST_NUMERIC_CONVERSION(unsigned int, uintmax_t, SIGN_PRESERVING_NARROW);
1261 TEST_NUMERIC_CONVERSION(int, float, SIGN_PRESERVING_NARROW);
1262 TEST_NUMERIC_CONVERSION(int, double, SIGN_PRESERVING_NARROW);
1263
1264 TEST_NUMERIC_CONVERSION(unsigned int, int, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
1265 TEST_NUMERIC_CONVERSION(unsigned int, int8_t, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
1266
1267 TEST_NUMERIC_CONVERSION(unsigned int, intmax_t, SIGN_TO_UNSIGN_NARROW);
1268 TEST_NUMERIC_CONVERSION(unsigned int, float, SIGN_TO_UNSIGN_NARROW);
1269 TEST_NUMERIC_CONVERSION(unsigned int, double, SIGN_TO_UNSIGN_NARROW);
1270
1271 TEST_NUMERIC_CONVERSION(int, unsigned int, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
1272 TEST_NUMERIC_CONVERSION(int, uintmax_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
1273 }
1274
TEST(SafeNumerics,IntMaxOperations)1275 TEST(SafeNumerics, IntMaxOperations) {
1276 TEST_NUMERIC_CONVERSION(intmax_t, intmax_t, SIGN_PRESERVING_VALUE_PRESERVING);
1277 TEST_NUMERIC_CONVERSION(uintmax_t, uintmax_t,
1278 SIGN_PRESERVING_VALUE_PRESERVING);
1279 TEST_NUMERIC_CONVERSION(intmax_t, int, SIGN_PRESERVING_VALUE_PRESERVING);
1280 TEST_NUMERIC_CONVERSION(uintmax_t, unsigned int,
1281 SIGN_PRESERVING_VALUE_PRESERVING);
1282 TEST_NUMERIC_CONVERSION(intmax_t, unsigned int,
1283 SIGN_PRESERVING_VALUE_PRESERVING);
1284 TEST_NUMERIC_CONVERSION(intmax_t, uint8_t, SIGN_PRESERVING_VALUE_PRESERVING);
1285
1286 TEST_NUMERIC_CONVERSION(intmax_t, float, SIGN_PRESERVING_NARROW);
1287 TEST_NUMERIC_CONVERSION(intmax_t, double, SIGN_PRESERVING_NARROW);
1288
1289 TEST_NUMERIC_CONVERSION(uintmax_t, int, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
1290 TEST_NUMERIC_CONVERSION(uintmax_t, int8_t, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
1291
1292 TEST_NUMERIC_CONVERSION(uintmax_t, float, SIGN_TO_UNSIGN_NARROW);
1293 TEST_NUMERIC_CONVERSION(uintmax_t, double, SIGN_TO_UNSIGN_NARROW);
1294
1295 TEST_NUMERIC_CONVERSION(intmax_t, uintmax_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
1296 }
1297
TEST(SafeNumerics,FloatOperations)1298 TEST(SafeNumerics, FloatOperations) {
1299 TEST_NUMERIC_CONVERSION(float, intmax_t, SIGN_PRESERVING_VALUE_PRESERVING);
1300 TEST_NUMERIC_CONVERSION(float, uintmax_t, SIGN_PRESERVING_VALUE_PRESERVING);
1301 TEST_NUMERIC_CONVERSION(float, int, SIGN_PRESERVING_VALUE_PRESERVING);
1302 TEST_NUMERIC_CONVERSION(float, unsigned int,
1303 SIGN_PRESERVING_VALUE_PRESERVING);
1304
1305 TEST_NUMERIC_CONVERSION(float, double, SIGN_PRESERVING_NARROW);
1306 }
1307
TEST(SafeNumerics,DoubleOperations)1308 TEST(SafeNumerics, DoubleOperations) {
1309 TEST_NUMERIC_CONVERSION(double, intmax_t, SIGN_PRESERVING_VALUE_PRESERVING);
1310 TEST_NUMERIC_CONVERSION(double, uintmax_t, SIGN_PRESERVING_VALUE_PRESERVING);
1311 TEST_NUMERIC_CONVERSION(double, int, SIGN_PRESERVING_VALUE_PRESERVING);
1312 TEST_NUMERIC_CONVERSION(double, unsigned int,
1313 SIGN_PRESERVING_VALUE_PRESERVING);
1314 }
1315
TEST(SafeNumerics,SizeTOperations)1316 TEST(SafeNumerics, SizeTOperations) {
1317 TEST_NUMERIC_CONVERSION(size_t, int, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
1318 TEST_NUMERIC_CONVERSION(int, size_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
1319 }
1320
1321 // A one-off test to ensure StrictNumeric won't resolve to an incorrect type.
1322 // If this fails we'll just get a compiler error on an ambiguous overload.
TestOverload(int)1323 int TestOverload(int) { // Overload fails.
1324 return 0;
1325 }
TestOverload(uint8_t)1326 uint8_t TestOverload(uint8_t) { // Overload fails.
1327 return 0;
1328 }
TestOverload(size_t)1329 size_t TestOverload(size_t) { // Overload succeeds.
1330 return 0;
1331 }
1332
1333 static_assert(
1334 std::is_same<decltype(TestOverload(StrictNumeric<int>())), int>::value,
1335 "");
1336 static_assert(std::is_same<decltype(TestOverload(StrictNumeric<size_t>())),
1337 size_t>::value,
1338 "");
1339
1340 template <typename T>
1341 struct CastTest1 {
NaNbase::internal::CastTest11342 static constexpr T NaN() { return -1; }
maxbase::internal::CastTest11343 static constexpr T max() { return numeric_limits<T>::max() - 1; }
Overflowbase::internal::CastTest11344 static constexpr T Overflow() { return max(); }
lowestbase::internal::CastTest11345 static constexpr T lowest() { return numeric_limits<T>::lowest() + 1; }
Underflowbase::internal::CastTest11346 static constexpr T Underflow() { return lowest(); }
1347 };
1348
1349 template <typename T>
1350 struct CastTest2 {
NaNbase::internal::CastTest21351 static constexpr T NaN() { return 11; }
maxbase::internal::CastTest21352 static constexpr T max() { return 10; }
Overflowbase::internal::CastTest21353 static constexpr T Overflow() { return max(); }
lowestbase::internal::CastTest21354 static constexpr T lowest() { return 1; }
Underflowbase::internal::CastTest21355 static constexpr T Underflow() { return lowest(); }
1356 };
1357
TEST(SafeNumerics,CastTests)1358 TEST(SafeNumerics, CastTests) {
1359 // MSVC catches and warns that we're forcing saturation in these tests.
1360 // Since that's intentional, we need to shut this warning off.
1361 #if defined(COMPILER_MSVC)
1362 #pragma warning(disable : 4756)
1363 #endif
1364
1365 int small_positive = 1;
1366 int small_negative = -1;
1367 double double_small = 1.0;
1368 double double_large = numeric_limits<double>::max();
1369 double double_infinity = numeric_limits<float>::infinity();
1370 double double_large_int = numeric_limits<int>::max();
1371 double double_small_int = numeric_limits<int>::lowest();
1372
1373 // Just test that the casts compile, since the other tests cover logic.
1374 EXPECT_EQ(0, checked_cast<int>(static_cast<size_t>(0)));
1375 EXPECT_EQ(0, strict_cast<int>(static_cast<char>(0)));
1376 EXPECT_EQ(0, strict_cast<int>(static_cast<unsigned char>(0)));
1377 EXPECT_EQ(0U, strict_cast<unsigned>(static_cast<unsigned char>(0)));
1378 EXPECT_EQ(1ULL, static_cast<uint64_t>(StrictNumeric<size_t>(1U)));
1379 EXPECT_EQ(1ULL, static_cast<uint64_t>(SizeT(1U)));
1380 EXPECT_EQ(1U, static_cast<size_t>(StrictNumeric<unsigned>(1U)));
1381
1382 EXPECT_TRUE(CheckedNumeric<uint64_t>(StrictNumeric<unsigned>(1U)).IsValid());
1383 EXPECT_TRUE(CheckedNumeric<int>(StrictNumeric<unsigned>(1U)).IsValid());
1384 EXPECT_FALSE(CheckedNumeric<unsigned>(StrictNumeric<int>(-1)).IsValid());
1385
1386 EXPECT_TRUE(IsValueNegative(-1));
1387 EXPECT_TRUE(IsValueNegative(numeric_limits<int>::lowest()));
1388 EXPECT_FALSE(IsValueNegative(numeric_limits<unsigned>::lowest()));
1389 EXPECT_TRUE(IsValueNegative(numeric_limits<double>::lowest()));
1390 EXPECT_FALSE(IsValueNegative(0));
1391 EXPECT_FALSE(IsValueNegative(1));
1392 EXPECT_FALSE(IsValueNegative(0u));
1393 EXPECT_FALSE(IsValueNegative(1u));
1394 EXPECT_FALSE(IsValueNegative(numeric_limits<int>::max()));
1395 EXPECT_FALSE(IsValueNegative(numeric_limits<unsigned>::max()));
1396 EXPECT_FALSE(IsValueNegative(numeric_limits<double>::max()));
1397
1398 // These casts and coercions will fail to compile:
1399 // EXPECT_EQ(0, strict_cast<int>(static_cast<size_t>(0)));
1400 // EXPECT_EQ(0, strict_cast<size_t>(static_cast<int>(0)));
1401 // EXPECT_EQ(1ULL, StrictNumeric<size_t>(1));
1402 // EXPECT_EQ(1, StrictNumeric<size_t>(1U));
1403
1404 // Test various saturation corner cases.
1405 EXPECT_EQ(saturated_cast<int>(small_negative),
1406 static_cast<int>(small_negative));
1407 EXPECT_EQ(saturated_cast<int>(small_positive),
1408 static_cast<int>(small_positive));
1409 EXPECT_EQ(saturated_cast<unsigned>(small_negative), static_cast<unsigned>(0));
1410 EXPECT_EQ(saturated_cast<int>(double_small), static_cast<int>(double_small));
1411 EXPECT_EQ(saturated_cast<int>(double_large), numeric_limits<int>::max());
1412 EXPECT_EQ(saturated_cast<float>(double_large), double_infinity);
1413 EXPECT_EQ(saturated_cast<float>(-double_large), -double_infinity);
1414 EXPECT_EQ(numeric_limits<int>::lowest(),
1415 saturated_cast<int>(double_small_int));
1416 EXPECT_EQ(numeric_limits<int>::max(), saturated_cast<int>(double_large_int));
1417
1418 // Test the saturated cast overrides.
1419 using FloatLimits = numeric_limits<float>;
1420 using IntLimits = numeric_limits<int>;
1421 EXPECT_EQ(-1, (saturated_cast<int, CastTest1>(FloatLimits::quiet_NaN())));
1422 EXPECT_EQ(CastTest1<int>::max(),
1423 (saturated_cast<int, CastTest1>(FloatLimits::infinity())));
1424 EXPECT_EQ(CastTest1<int>::max(),
1425 (saturated_cast<int, CastTest1>(FloatLimits::max())));
1426 EXPECT_EQ(CastTest1<int>::max(),
1427 (saturated_cast<int, CastTest1>(float(IntLimits::max()))));
1428 EXPECT_EQ(CastTest1<int>::lowest(),
1429 (saturated_cast<int, CastTest1>(-FloatLimits::infinity())));
1430 EXPECT_EQ(CastTest1<int>::lowest(),
1431 (saturated_cast<int, CastTest1>(FloatLimits::lowest())));
1432 EXPECT_EQ(0, (saturated_cast<int, CastTest1>(0.0)));
1433 EXPECT_EQ(1, (saturated_cast<int, CastTest1>(1.0)));
1434 EXPECT_EQ(-1, (saturated_cast<int, CastTest1>(-1.0)));
1435 EXPECT_EQ(0, (saturated_cast<int, CastTest1>(0)));
1436 EXPECT_EQ(1, (saturated_cast<int, CastTest1>(1)));
1437 EXPECT_EQ(-1, (saturated_cast<int, CastTest1>(-1)));
1438 EXPECT_EQ(CastTest1<int>::lowest(),
1439 (saturated_cast<int, CastTest1>(float(IntLimits::lowest()))));
1440 EXPECT_EQ(11, (saturated_cast<int, CastTest2>(FloatLimits::quiet_NaN())));
1441 EXPECT_EQ(10, (saturated_cast<int, CastTest2>(FloatLimits::infinity())));
1442 EXPECT_EQ(10, (saturated_cast<int, CastTest2>(FloatLimits::max())));
1443 EXPECT_EQ(1, (saturated_cast<int, CastTest2>(-FloatLimits::infinity())));
1444 EXPECT_EQ(1, (saturated_cast<int, CastTest2>(FloatLimits::lowest())));
1445 EXPECT_EQ(1, (saturated_cast<int, CastTest2>(0U)));
1446
1447 float not_a_number = std::numeric_limits<float>::infinity() -
1448 std::numeric_limits<float>::infinity();
1449 EXPECT_TRUE(std::isnan(not_a_number));
1450 EXPECT_EQ(0, saturated_cast<int>(not_a_number));
1451
1452 // Test the CheckedNumeric value extractions functions.
1453 auto int8_min = MakeCheckedNum(numeric_limits<int8_t>::lowest());
1454 auto int8_max = MakeCheckedNum(numeric_limits<int8_t>::max());
1455 auto double_max = MakeCheckedNum(numeric_limits<double>::max());
1456 static_assert(
1457 std::is_same<int16_t,
1458 decltype(int8_min.ValueOrDie<int16_t>())::type>::value,
1459 "ValueOrDie returning incorrect type.");
1460 static_assert(
1461 std::is_same<int16_t,
1462 decltype(int8_min.ValueOrDefault<int16_t>(0))::type>::value,
1463 "ValueOrDefault returning incorrect type.");
1464 EXPECT_FALSE(IsValidForType<uint8_t>(int8_min));
1465 EXPECT_TRUE(IsValidForType<uint8_t>(int8_max));
1466 EXPECT_EQ(static_cast<int>(numeric_limits<int8_t>::lowest()),
1467 ValueOrDieForType<int>(int8_min));
1468 EXPECT_TRUE(IsValidForType<uint32_t>(int8_max));
1469 EXPECT_EQ(static_cast<int>(numeric_limits<int8_t>::max()),
1470 ValueOrDieForType<int>(int8_max));
1471 EXPECT_EQ(0, ValueOrDefaultForType<int>(double_max, 0));
1472 uint8_t uint8_dest = 0;
1473 int16_t int16_dest = 0;
1474 double double_dest = 0;
1475 EXPECT_TRUE(int8_max.AssignIfValid(&uint8_dest));
1476 EXPECT_EQ(static_cast<uint8_t>(numeric_limits<int8_t>::max()), uint8_dest);
1477 EXPECT_FALSE(int8_min.AssignIfValid(&uint8_dest));
1478 EXPECT_TRUE(int8_max.AssignIfValid(&int16_dest));
1479 EXPECT_EQ(static_cast<int16_t>(numeric_limits<int8_t>::max()), int16_dest);
1480 EXPECT_TRUE(int8_min.AssignIfValid(&int16_dest));
1481 EXPECT_EQ(static_cast<int16_t>(numeric_limits<int8_t>::lowest()), int16_dest);
1482 EXPECT_FALSE(double_max.AssignIfValid(&uint8_dest));
1483 EXPECT_FALSE(double_max.AssignIfValid(&int16_dest));
1484 EXPECT_TRUE(double_max.AssignIfValid(&double_dest));
1485 EXPECT_EQ(numeric_limits<double>::max(), double_dest);
1486 EXPECT_EQ(1, checked_cast<int>(StrictNumeric<int>(1)));
1487 EXPECT_EQ(1, saturated_cast<int>(StrictNumeric<int>(1)));
1488 EXPECT_EQ(1, strict_cast<int>(StrictNumeric<int>(1)));
1489
1490 enum class EnumTest { kOne = 1 };
1491 EXPECT_EQ(1, checked_cast<int>(EnumTest::kOne));
1492 EXPECT_EQ(1, saturated_cast<int>(EnumTest::kOne));
1493 EXPECT_EQ(1, strict_cast<int>(EnumTest::kOne));
1494 }
1495
TEST(SafeNumerics,IsValueInRangeForNumericType)1496 TEST(SafeNumerics, IsValueInRangeForNumericType) {
1497 EXPECT_TRUE(IsValueInRangeForNumericType<uint32_t>(0));
1498 EXPECT_TRUE(IsValueInRangeForNumericType<uint32_t>(1));
1499 EXPECT_TRUE(IsValueInRangeForNumericType<uint32_t>(2));
1500 EXPECT_FALSE(IsValueInRangeForNumericType<uint32_t>(-1));
1501 EXPECT_TRUE(IsValueInRangeForNumericType<uint32_t>(0xffffffffu));
1502 EXPECT_TRUE(IsValueInRangeForNumericType<uint32_t>(UINT64_C(0xffffffff)));
1503 EXPECT_FALSE(IsValueInRangeForNumericType<uint32_t>(UINT64_C(0x100000000)));
1504 EXPECT_FALSE(IsValueInRangeForNumericType<uint32_t>(UINT64_C(0x100000001)));
1505 EXPECT_FALSE(IsValueInRangeForNumericType<uint32_t>(
1506 std::numeric_limits<int32_t>::lowest()));
1507 EXPECT_FALSE(IsValueInRangeForNumericType<uint32_t>(
1508 std::numeric_limits<int64_t>::lowest()));
1509
1510 EXPECT_TRUE(IsValueInRangeForNumericType<int32_t>(0));
1511 EXPECT_TRUE(IsValueInRangeForNumericType<int32_t>(1));
1512 EXPECT_TRUE(IsValueInRangeForNumericType<int32_t>(2));
1513 EXPECT_TRUE(IsValueInRangeForNumericType<int32_t>(-1));
1514 EXPECT_TRUE(IsValueInRangeForNumericType<int32_t>(0x7fffffff));
1515 EXPECT_TRUE(IsValueInRangeForNumericType<int32_t>(0x7fffffffu));
1516 EXPECT_FALSE(IsValueInRangeForNumericType<int32_t>(0x80000000u));
1517 EXPECT_FALSE(IsValueInRangeForNumericType<int32_t>(0xffffffffu));
1518 EXPECT_FALSE(IsValueInRangeForNumericType<int32_t>(INT64_C(0x80000000)));
1519 EXPECT_FALSE(IsValueInRangeForNumericType<int32_t>(INT64_C(0xffffffff)));
1520 EXPECT_FALSE(IsValueInRangeForNumericType<int32_t>(INT64_C(0x100000000)));
1521 EXPECT_TRUE(IsValueInRangeForNumericType<int32_t>(
1522 std::numeric_limits<int32_t>::lowest()));
1523 EXPECT_TRUE(IsValueInRangeForNumericType<int32_t>(
1524 static_cast<int64_t>(std::numeric_limits<int32_t>::lowest())));
1525 EXPECT_FALSE(IsValueInRangeForNumericType<int32_t>(
1526 static_cast<int64_t>(std::numeric_limits<int32_t>::lowest()) - 1));
1527 EXPECT_FALSE(IsValueInRangeForNumericType<int32_t>(
1528 std::numeric_limits<int64_t>::lowest()));
1529
1530 EXPECT_TRUE(IsValueInRangeForNumericType<uint64_t>(0));
1531 EXPECT_TRUE(IsValueInRangeForNumericType<uint64_t>(1));
1532 EXPECT_TRUE(IsValueInRangeForNumericType<uint64_t>(2));
1533 EXPECT_FALSE(IsValueInRangeForNumericType<uint64_t>(-1));
1534 EXPECT_TRUE(IsValueInRangeForNumericType<uint64_t>(0xffffffffu));
1535 EXPECT_TRUE(IsValueInRangeForNumericType<uint64_t>(UINT64_C(0xffffffff)));
1536 EXPECT_TRUE(IsValueInRangeForNumericType<uint64_t>(UINT64_C(0x100000000)));
1537 EXPECT_TRUE(IsValueInRangeForNumericType<uint64_t>(UINT64_C(0x100000001)));
1538 EXPECT_FALSE(IsValueInRangeForNumericType<uint64_t>(
1539 std::numeric_limits<int32_t>::lowest()));
1540 EXPECT_FALSE(IsValueInRangeForNumericType<uint64_t>(INT64_C(-1)));
1541 EXPECT_FALSE(IsValueInRangeForNumericType<uint64_t>(
1542 std::numeric_limits<int64_t>::lowest()));
1543
1544 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(0));
1545 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(1));
1546 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(2));
1547 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(-1));
1548 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(0x7fffffff));
1549 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(0x7fffffffu));
1550 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(0x80000000u));
1551 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(0xffffffffu));
1552 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(INT64_C(0x80000000)));
1553 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(INT64_C(0xffffffff)));
1554 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(INT64_C(0x100000000)));
1555 EXPECT_TRUE(
1556 IsValueInRangeForNumericType<int64_t>(INT64_C(0x7fffffffffffffff)));
1557 EXPECT_TRUE(
1558 IsValueInRangeForNumericType<int64_t>(UINT64_C(0x7fffffffffffffff)));
1559 EXPECT_FALSE(
1560 IsValueInRangeForNumericType<int64_t>(UINT64_C(0x8000000000000000)));
1561 EXPECT_FALSE(
1562 IsValueInRangeForNumericType<int64_t>(UINT64_C(0xffffffffffffffff)));
1563 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(
1564 std::numeric_limits<int32_t>::lowest()));
1565 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(
1566 static_cast<int64_t>(std::numeric_limits<int32_t>::lowest())));
1567 EXPECT_TRUE(IsValueInRangeForNumericType<int64_t>(
1568 std::numeric_limits<int64_t>::lowest()));
1569 }
1570
TEST(SafeNumerics,CompoundNumericOperations)1571 TEST(SafeNumerics, CompoundNumericOperations) {
1572 CheckedNumeric<int> a = 1;
1573 CheckedNumeric<int> b = 2;
1574 CheckedNumeric<int> c = 3;
1575 CheckedNumeric<int> d = 4;
1576 a += b;
1577 EXPECT_EQ(3, a.ValueOrDie());
1578 a -= c;
1579 EXPECT_EQ(0, a.ValueOrDie());
1580 d /= b;
1581 EXPECT_EQ(2, d.ValueOrDie());
1582 d *= d;
1583 EXPECT_EQ(4, d.ValueOrDie());
1584
1585 CheckedNumeric<int> too_large = std::numeric_limits<int>::max();
1586 EXPECT_TRUE(too_large.IsValid());
1587 too_large += d;
1588 EXPECT_FALSE(too_large.IsValid());
1589 too_large -= d;
1590 EXPECT_FALSE(too_large.IsValid());
1591 too_large /= d;
1592 EXPECT_FALSE(too_large.IsValid());
1593 }
1594
TEST(SafeNumerics,VariadicNumericOperations)1595 TEST(SafeNumerics, VariadicNumericOperations) {
1596 { // Synthetic scope to avoid variable naming collisions.
1597 auto a = CheckAdd(1, 2UL, MakeCheckedNum(3LL), 4).ValueOrDie();
1598 EXPECT_EQ(static_cast<decltype(a)::type>(10), a);
1599 auto b = CheckSub(MakeCheckedNum(20.0), 2UL, 4).ValueOrDie();
1600 EXPECT_EQ(static_cast<decltype(b)::type>(14.0), b);
1601 auto c = CheckMul(20.0, MakeCheckedNum(1), 5, 3UL).ValueOrDie();
1602 EXPECT_EQ(static_cast<decltype(c)::type>(300.0), c);
1603 auto d = CheckDiv(20.0, 2.0, MakeCheckedNum(5LL), -4).ValueOrDie();
1604 EXPECT_EQ(static_cast<decltype(d)::type>(-.5), d);
1605 auto e = CheckMod(MakeCheckedNum(20), 3).ValueOrDie();
1606 EXPECT_EQ(static_cast<decltype(e)::type>(2), e);
1607 auto f = CheckLsh(1, MakeCheckedNum(2)).ValueOrDie();
1608 EXPECT_EQ(static_cast<decltype(f)::type>(4), f);
1609 auto g = CheckRsh(4, MakeCheckedNum(2)).ValueOrDie();
1610 EXPECT_EQ(static_cast<decltype(g)::type>(1), g);
1611 auto h = CheckRsh(CheckAdd(1, 1, 1, 1), CheckSub(4, 2)).ValueOrDie();
1612 EXPECT_EQ(static_cast<decltype(h)::type>(1), h);
1613 }
1614
1615 {
1616 auto a = ClampAdd(1, 2UL, MakeClampedNum(3LL), 4);
1617 EXPECT_EQ(static_cast<decltype(a)::type>(10), a);
1618 auto b = ClampSub(MakeClampedNum(20.0), 2UL, 4);
1619 EXPECT_EQ(static_cast<decltype(b)::type>(14.0), b);
1620 auto c = ClampMul(20.0, MakeClampedNum(1), 5, 3UL);
1621 EXPECT_EQ(static_cast<decltype(c)::type>(300.0), c);
1622 auto d = ClampDiv(20.0, 2.0, MakeClampedNum(5LL), -4);
1623 EXPECT_EQ(static_cast<decltype(d)::type>(-.5), d);
1624 auto e = ClampMod(MakeClampedNum(20), 3);
1625 EXPECT_EQ(static_cast<decltype(e)::type>(2), e);
1626 auto f = ClampLsh(1, MakeClampedNum(2U));
1627 EXPECT_EQ(static_cast<decltype(f)::type>(4), f);
1628 auto g = ClampRsh(4, MakeClampedNum(2U));
1629 EXPECT_EQ(static_cast<decltype(g)::type>(1), g);
1630 auto h = ClampRsh(ClampAdd(1, 1, 1, 1), ClampSub(4U, 2));
1631 EXPECT_EQ(static_cast<decltype(h)::type>(1), h);
1632 }
1633 }
1634
1635 #if defined(__clang__)
1636 #pragma clang diagnostic pop // -Winteger-overflow
1637 #endif
1638
1639 } // namespace internal
1640 } // namespace base
1641