From b8e3ac4cd94d0347f481798e1b9331c2a94e83c8 Mon Sep 17 00:00:00 2001 From: Michael Platings Date: Fri, 19 Apr 2024 09:16:11 +0000 Subject: [PATCH] Fix undefined behaviour casting negative number to unsigned The intent of the cast was likely to ensure numeric values were printed instead of printing as char. Unary + achieves this better via integer promotion. --- test/framework/array.h | 34 +++++++++++++++++----------------- test/framework/utils.cpp | 3 ++- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/test/framework/array.h b/test/framework/array.h index f166432d3..7ad94af55 100644 --- a/test/framework/array.h +++ b/test/framework/array.h @@ -345,23 +345,23 @@ class Array2D : public TwoDimensional { }; // end of class Array2D // Compares two Array2D objects for equality. -#define EXPECT_EQ_ARRAY2D(lhs, rhs) \ - do { \ - ASSERT_EQ((lhs).width(), (rhs).width()) \ - << "Mismatch in width." << std::endl; \ - ASSERT_EQ((lhs).height(), (rhs).height()) \ - << "Mismatch in height." << std::endl; \ - ASSERT_EQ((lhs).channels(), (rhs).channels()) \ - << "Mismatch in channels." << std::endl; \ - auto mismatch = (lhs).compare_to((rhs)); \ - if (mismatch) { \ - auto [row, col] = *mismatch; \ - GTEST_FAIL() << "Mismatch at (row=" << row << ", col=" << col \ - << "): " << std::hex << std::showbase \ - << static_cast((lhs).at(row, col)[0]) << " vs " \ - << static_cast((rhs).at(row, col)[0]) << "." \ - << std::endl; \ - } \ +// Unary + is used to ensure values are printed as integers, not chars +#define EXPECT_EQ_ARRAY2D(lhs, rhs) \ + do { \ + ASSERT_EQ((lhs).width(), (rhs).width()) \ + << "Mismatch in width." << std::endl; \ + ASSERT_EQ((lhs).height(), (rhs).height()) \ + << "Mismatch in height." << std::endl; \ + ASSERT_EQ((lhs).channels(), (rhs).channels()) \ + << "Mismatch in channels." << std::endl; \ + auto mismatch = (lhs).compare_to((rhs)); \ + if (mismatch) { \ + auto [row, col] = *mismatch; \ + GTEST_FAIL() << "Mismatch at (row=" << row << ", col=" << col \ + << "): " << std::hex << std::showbase \ + << +(lhs).at(row, col)[0] << " vs " \ + << +(rhs).at(row, col)[0] << "." << std::endl; \ + } \ } while (0 != 0) // Compares two Array2D objects for inequality. diff --git a/test/framework/utils.cpp b/test/framework/utils.cpp index c79ec1335..a88f42a11 100644 --- a/test/framework/utils.cpp +++ b/test/framework/utils.cpp @@ -29,8 +29,9 @@ void dump(const TwoDimensional *elements) { for (size_t row = 0; row < elements->height(); ++row) { for (size_t column = 0; column < elements->width(); ++column) { ElementType value = elements->at(row, column)[0]; + // Unary + is used to ensure values are printed as integers, not chars std::cout << std::setw(2 * sizeof(ElementType)) << std::setfill('0') - << std::hex << (static_cast(value) & mask) << " "; + << std::hex << +(value & mask) << " "; } std::cout << std::endl; -- GitLab