created new file for gsl_narrow, might want to rename if we go this approach to have all exception prone logic to live here

This commit is contained in:
Jordan Maples 2020-08-11 17:11:14 -07:00
parent 63379b7935
commit 72ddfb7a40
3 changed files with 35 additions and 27 deletions

33
include/gsl/gsl_narrow Normal file
View File

@ -0,0 +1,33 @@
#ifndef GSL_NARROW_H
#define GSL_NARROW_H
#include <gsl/gsl_assert> // for Expects
#include <gsl/gsl_util> // for narrow_cast
namespace gsl
{
struct narrowing_error : public std::exception
{
};
// narrow() : a checked version of narrow_cast() that throws if the cast changed the value
template <class T, class U>
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // TODO: MSVC /analyze does not recognise noexcept(false)
constexpr
T narrow(U u) noexcept(false)
{
constexpr const bool is_different_signedness = (std::is_signed<T>::value != std::is_signed<U>::value);
const T t = narrow_cast<T>(u);
if (static_cast<U>(t) != u
|| (is_different_signedness
&& ((t < T{}) != (u < U{}))))
{
throw narrowing_error{};
}
return t;
}
}
#endif // GSL_NARROW_H

View File

@ -86,31 +86,6 @@ constexpr T narrow_cast(U&& u) noexcept
return static_cast<T>(std::forward<U>(u));
}
struct narrowing_error : public std::exception
{
};
// narrow() : a checked version of narrow_cast() that throws if the cast changed the value
template <class T, class U>
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // TODO: MSVC /analyze does not recognise noexcept(false)
constexpr
T narrow(U u) noexcept(false)
{
constexpr const bool is_different_signedness = (std::is_signed<T>::value != std::is_signed<U>::value);
const T t = narrow_cast<T>(u);
if (static_cast<U>(t) != u
|| (is_different_signedness
&& ((t < T{}) != (u < U{}))))
{
throw narrowing_error{};
}
return t;
}
//
// at() - Bounds-checked way of accessing builtin arrays, std::array, std::vector
//

View File

@ -16,8 +16,8 @@
#include <gtest/gtest.h>
#include <gsl/gsl_util> // for narrow, finally, narrow_cast, narrowing_e...
#include <gsl/gsl_util> // finally, narrow_cast
#include <gsl/gsl_narrow> // for narrow, narrowing_error
#include <algorithm> // for move
#include <functional> // for reference_wrapper, _Bind_helper<>::type
#include <limits> // for numeric_limits