1 #include "llvm/Support/CheckedArithmetic.h"
2 #include "gtest/gtest.h"
8 TEST(CheckedArithmetic, CheckedAdd) {
10 const int64_t Max = std::numeric_limits<int64_t>::max();
11 const int64_t Min = std::numeric_limits<int64_t>::min();
12 EXPECT_EQ(checkedAdd<int64_t>(Max, Max, &Out), true);
13 EXPECT_EQ(checkedAdd<int64_t>(Min, -1, &Out), true);
14 EXPECT_EQ(checkedAdd<int64_t>(Max, 1, &Out), true);
15 EXPECT_EQ(checkedAdd<int64_t>(10, 1, &Out), false);
19 TEST(CheckedArithmetic, CheckedAddSmall) {
21 const int16_t Max = std::numeric_limits<int16_t>::max();
22 const int16_t Min = std::numeric_limits<int16_t>::min();
23 EXPECT_EQ(checkedAdd<int16_t>(Max, Max, &Out), true);
24 EXPECT_EQ(checkedAdd<int16_t>(Min, -1, &Out), true);
25 EXPECT_EQ(checkedAdd<int16_t>(Max, 1, &Out), true);
26 EXPECT_EQ(checkedAdd<int16_t>(10, 1, &Out), false);
30 TEST(CheckedArithmetic, CheckedMul) {
32 const int64_t Max = std::numeric_limits<int64_t>::max();
33 const int64_t Min = std::numeric_limits<int64_t>::min();
34 EXPECT_EQ(checkedMul<int64_t>(Max, 2, &Out), true);
35 EXPECT_EQ(checkedMul<int64_t>(Max, Max, &Out), true);
36 EXPECT_EQ(checkedMul<int64_t>(Min, 2, &Out), true);
37 EXPECT_EQ(checkedMul<int64_t>(10, 2, &Out), false);
41 TEST(CheckedArithmetic, CheckedMulSmall) {
43 const int16_t Max = std::numeric_limits<int16_t>::max();
44 const int16_t Min = std::numeric_limits<int16_t>::min();
45 EXPECT_EQ(checkedMul<int16_t>(Max, 2, &Out), true);
46 EXPECT_EQ(checkedMul<int16_t>(Max, Max, &Out), true);
47 EXPECT_EQ(checkedMul<int16_t>(Min, 2, &Out), true);
48 EXPECT_EQ(checkedMul<int16_t>(10, 2, &Out), false);
52 TEST(CheckedArithmetic, CheckedAddUnsigned) {
54 const uint64_t Max = std::numeric_limits<uint64_t>::max();
55 EXPECT_EQ(checkedAddUnsigned<uint64_t>(Max, Max, &Out), true);
56 EXPECT_EQ(checkedAddUnsigned<uint64_t>(Max, 1, &Out), true);
57 EXPECT_EQ(checkedAddUnsigned<uint64_t>(10, 1, &Out), false);
58 EXPECT_EQ(Out, uint64_t(11));
61 TEST(CheckedArithmetic, CheckedMulUnsigned) {
63 const uint64_t Max = std::numeric_limits<uint64_t>::max();
64 EXPECT_EQ(checkedMulUnsigned<uint64_t>(Max, 2, &Out), true);
65 EXPECT_EQ(checkedMulUnsigned<uint64_t>(Max, Max, &Out), true);
66 EXPECT_EQ(checkedMulUnsigned<uint64_t>(10, 2, &Out), false);
67 EXPECT_EQ(Out, uint64_t(20));