Skip to content

Commit

Permalink
Make narrow accept types with different signs
Browse files Browse the repository at this point in the history
  • Loading branch information
albin-johansson committed Oct 21, 2024
1 parent 64825dd commit 968e13f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
12 changes: 5 additions & 7 deletions source/base/lib/inc/tactile/base/numeric/conversion.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

#pragma once

#include <concepts> // integral
#include <limits> // numeric_limits
#include <stdexcept> // underflow_error, overflow_error
#include <type_traits> // is_signed_v
#include <utility> // cmp_less, cmp_greater
#include <concepts> // integral, same_as
#include <limits> // numeric_limits
#include <stdexcept> // underflow_error, overflow_error
#include <utility> // cmp_less, cmp_greater

namespace tactile {

Expand All @@ -27,10 +26,9 @@ namespace tactile {
template <std::integral To, std::integral From>
[[nodiscard]] constexpr auto narrow(const From from) -> To
{
static_assert(std::is_signed_v<To> == std::is_signed_v<From>);
static_assert(sizeof(To) <= sizeof(From));

if constexpr (sizeof(To) == sizeof(From)) {
if constexpr (std::same_as<To, From>) {
return static_cast<To>(from);
}
else {
Expand Down
9 changes: 9 additions & 0 deletions source/base/test/src/numeric/conversion_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,27 @@ TEST(Conversion, NarrowUnsignedValues)
EXPECT_EQ(narrow<std::uint16_t>(std::uint32_t {0xABCD}), std::uint16_t {0xABCD});
}

// tactile::narrow
TEST(Conversion, NarrowDifferentSignValues)
{
EXPECT_EQ(narrow<std::uint8_t>(std::int16_t {123}), std::uint8_t {123});
EXPECT_EQ(narrow<std::int16_t>(std::uint32_t {8432}), std::int16_t {8432});
}

// tactile::narrow
TEST(Conversion, NarrowUnderflow)
{
EXPECT_THROW((void) narrow<std::int8_t>(std::int16_t {kMinS8} - 1), std::underflow_error);
EXPECT_THROW((void) narrow<std::int16_t>(std::int32_t {kMinS16} - 1), std::underflow_error);
EXPECT_THROW((void) narrow<std::uint8_t>(std::int8_t {-1}), std::underflow_error);
}

// tactile::narrow
TEST(Conversion, NarrowOverflow)
{
EXPECT_THROW((void) narrow<std::int8_t>(std::int16_t {kMaxS8} + 1), std::overflow_error);
EXPECT_THROW((void) narrow<std::int16_t>(std::int32_t {kMaxS16} + 1), std::overflow_error);
EXPECT_THROW((void) narrow<std::int8_t>(std::uint8_t {129}), std::overflow_error);
}

} // namespace
Expand Down

0 comments on commit 968e13f

Please sign in to comment.