TEST(SafeMath, Add) { // Adding 1 overflows 0x7ff... to 0x800... aka max and min.
EXPECT_EQ(SafeAdd(std::numeric_limits<int32_t>::max(), 1),
std::numeric_limits<int32_t>::min());
EXPECT_EQ(SafeAdd(std::numeric_limits<int64_t>::max(), 1),
std::numeric_limits<int64_t>::min());
// Vanilla arithmetic should work too.
EXPECT_EQ(SafeAdd(std::numeric_limits<int32_t>::max() - 1, 1),
std::numeric_limits<int32_t>::max());
EXPECT_EQ(SafeAdd(std::numeric_limits<int64_t>::max() - 1, 1),
std::numeric_limits<int64_t>::max());
// Test sign extension of smaller operand sizes.
EXPECT_EQ(SafeAdd(int32_t(1), int8_t(-1)), 0);
EXPECT_EQ(SafeAdd(int64_t(1), int8_t(-1)), 0);
}
TEST(SafeMath, Mul) { // Multiplying by 2 overflows 0x7ff...f to 0xfff...e aka max and -2.
EXPECT_EQ(SafeMul(std::numeric_limits<int32_t>::max(), 2),
-2);
EXPECT_EQ(SafeMul(std::numeric_limits<int64_t>::max(), 2),
-2);
// Vanilla arithmetic should work too.
EXPECT_EQ(SafeMul(std::numeric_limits<int32_t>::max() / 2, 2),
std::numeric_limits<int32_t>::max() - 1); // -1 as LSB is lost by division.
EXPECT_EQ(SafeMul(std::numeric_limits<int64_t>::max() / 2, 2),
std::numeric_limits<int64_t>::max() - 1); // -1 as LSB is lost by division.
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.