/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_NARROW_H #define GSL_NARROW_H #include "./assert" // for GSL_SUPPRESS #include "./util" // for narrow_cast #include // for std::exception namespace gsl { namespace details { template constexpr bool static_cast_is_defined(U u, /*is_floating_point_to_integral=*/std::true_type) { if (std::is_same::type, bool>::value) { return true; } U upper_bound{1}; for (int i = 0; i < std::numeric_limits::digits; i++) { upper_bound *= std::numeric_limits::radix; } if (u >= U{}) { return u < upper_bound; } if (!std::is_signed::value) { return u > U{-1}; } return u + upper_bound > U{-1}; } template constexpr bool static_cast_is_defined(U, /*is_floating_point_to_integral=*/std::false_type) { return true; } } // namespace details struct narrowing_error : public std::exception { const char* what() const noexcept override { return "narrowing_error"; } }; // narrow() : a checked version of narrow_cast() that throws if the cast changed the value template ::value>::type* = nullptr> GSL_SUPPRESS(type.1) constexpr T narrow(U u) { constexpr const bool is_different_signedness = (std::is_signed::value != std::is_signed::value); using is_floating_point_to_integral = std::integral_constant::value && std::is_floating_point::value>; if (!details::static_cast_is_defined(u, is_floating_point_to_integral{})) { throw narrowing_error{}; } GSL_SUPPRESS(es.103) // don't overflow GSL_SUPPRESS(es.104) // don't underflow const T t = narrow_cast(u); #if defined(__clang__) || defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif // Note: NaN will always throw, since NaN != NaN if (static_cast(t) != u || (is_different_signedness && ((t < T{}) != (u < U{})))) { throw narrowing_error{}; } #if defined(__clang__) || defined(__GNUC__) #pragma GCC diagnostic pop #endif return t; } template ::value>::type* = nullptr> GSL_SUPPRESS(type.1) constexpr T narrow(U u) { const T t = narrow_cast(u); if (static_cast(t) != u) { throw narrowing_error{}; } return t; } } // namespace gsl #endif // GSL_NARROW_H