From 968e13fc99250f66b74d1b66029dd016ee76b8d2 Mon Sep 17 00:00:00 2001 From: Albin Johansson Date: Mon, 21 Oct 2024 18:29:04 +0200 Subject: [PATCH] Make narrow accept types with different signs --- .../base/lib/inc/tactile/base/numeric/conversion.hpp | 12 +++++------- source/base/test/src/numeric/conversion_test.cpp | 9 +++++++++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/source/base/lib/inc/tactile/base/numeric/conversion.hpp b/source/base/lib/inc/tactile/base/numeric/conversion.hpp index 6b4d684ca..3c258e3a3 100644 --- a/source/base/lib/inc/tactile/base/numeric/conversion.hpp +++ b/source/base/lib/inc/tactile/base/numeric/conversion.hpp @@ -2,11 +2,10 @@ #pragma once -#include // integral -#include // numeric_limits -#include // underflow_error, overflow_error -#include // is_signed_v -#include // cmp_less, cmp_greater +#include // integral, same_as +#include // numeric_limits +#include // underflow_error, overflow_error +#include // cmp_less, cmp_greater namespace tactile { @@ -27,10 +26,9 @@ namespace tactile { template [[nodiscard]] constexpr auto narrow(const From from) -> To { - static_assert(std::is_signed_v == std::is_signed_v); static_assert(sizeof(To) <= sizeof(From)); - if constexpr (sizeof(To) == sizeof(From)) { + if constexpr (std::same_as) { return static_cast(from); } else { diff --git a/source/base/test/src/numeric/conversion_test.cpp b/source/base/test/src/numeric/conversion_test.cpp index f78953bb4..0e6a89900 100644 --- a/source/base/test/src/numeric/conversion_test.cpp +++ b/source/base/test/src/numeric/conversion_test.cpp @@ -55,11 +55,19 @@ TEST(Conversion, NarrowUnsignedValues) EXPECT_EQ(narrow(std::uint32_t {0xABCD}), std::uint16_t {0xABCD}); } +// tactile::narrow +TEST(Conversion, NarrowDifferentSignValues) +{ + EXPECT_EQ(narrow(std::int16_t {123}), std::uint8_t {123}); + EXPECT_EQ(narrow(std::uint32_t {8432}), std::int16_t {8432}); +} + // tactile::narrow TEST(Conversion, NarrowUnderflow) { EXPECT_THROW((void) narrow(std::int16_t {kMinS8} - 1), std::underflow_error); EXPECT_THROW((void) narrow(std::int32_t {kMinS16} - 1), std::underflow_error); + EXPECT_THROW((void) narrow(std::int8_t {-1}), std::underflow_error); } // tactile::narrow @@ -67,6 +75,7 @@ TEST(Conversion, NarrowOverflow) { EXPECT_THROW((void) narrow(std::int16_t {kMaxS8} + 1), std::overflow_error); EXPECT_THROW((void) narrow(std::int32_t {kMaxS16} + 1), std::overflow_error); + EXPECT_THROW((void) narrow(std::uint8_t {129}), std::overflow_error); } } // namespace