Merge pull request #262 from chfast/narrow

narrow: check for changed sign
This commit is contained in:
Neil MacIntosh 2016-02-19 17:19:51 -08:00
commit ad0905c08b
2 changed files with 66 additions and 37 deletions

View File

@ -22,6 +22,7 @@
#include "gsl_assert.h" // Ensures/Expects #include "gsl_assert.h" // Ensures/Expects
#include <array> #include <array>
#include <utility> #include <utility>
#include <type_traits>
#include <exception> #include <exception>
#ifdef _MSC_VER #ifdef _MSC_VER
@ -39,6 +40,7 @@
// turn off some misguided warnings // turn off some misguided warnings
#pragma warning(push) #pragma warning(push)
#pragma warning(disable: 4351) // warns about newly introduced aggregate initializer behavior #pragma warning(disable: 4351) // warns about newly introduced aggregate initializer behavior
#pragma warning(disable: 4127) // conditional expression is constant
#endif // _MSC_VER <= 1800 #endif // _MSC_VER <= 1800
@ -90,10 +92,24 @@ inline constexpr T narrow_cast(U u) noexcept
struct narrowing_error : public std::exception {}; struct narrowing_error : public std::exception {};
namespace details
{
template<class T, class U>
struct is_same_signedness : public std::integral_constant<bool, std::is_signed<T>::value == std::is_signed<U>::value>
{};
}
// narrow() : a checked version of narrow_cast() that throws if the cast changed the value // narrow() : a checked version of narrow_cast() that throws if the cast changed the value
template<class T, class U> template<class T, class U>
inline T narrow(U u) inline T narrow(U u)
{ T t = narrow_cast<T>(u); if (static_cast<U>(t) != u) throw narrowing_error(); return t; } {
T t = narrow_cast<T>(u);
if (static_cast<U>(t) != u)
throw narrowing_error();
if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{})))
throw narrowing_error();
return t;
}
// //
// at() - Bounds-checked way of accessing static arrays, std::array, std::vector // at() - Bounds-checked way of accessing static arrays, std::array, std::vector

View File

@ -97,6 +97,19 @@ SUITE(utils_tests)
n = 300; n = 300;
CHECK_THROW(narrow<char>(n), narrowing_error); CHECK_THROW(narrow<char>(n), narrowing_error);
const auto int32_max = std::numeric_limits<int32_t>::max();
const auto int32_min = std::numeric_limits<int32_t>::min();
CHECK(narrow<uint32_t>(int32_t(0)) == 0);
CHECK(narrow<uint32_t>(int32_t(1)) == 1);
CHECK(narrow<uint32_t>(int32_max) == int32_max);
CHECK_THROW(narrow<uint32_t>(int32_t(-1)), narrowing_error);
CHECK_THROW(narrow<uint32_t>(int32_min), narrowing_error);
n = -42;
CHECK_THROW(narrow<unsigned>(n), narrowing_error);
} }
} }