narrow: Also check if a value has changed sign after cast.

Fixes https://github.com/Microsoft/GSL/issues/222.
This commit is contained in:
Paweł Bylica 2016-02-08 12:34:21 +01:00
parent 0be53d99ef
commit 6a4f2512b7
2 changed files with 50 additions and 37 deletions

View File

@ -93,7 +93,7 @@ struct narrowing_error : public std::exception {};
// 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 || (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);
} }
} }