| 1 | /* Copyright 2022 Joaquin M Lopez Munoz. |
|---|---|
| 2 | * Distributed under the Boost Software License, Version 1.0. |
| 3 | * (See accompanying file LICENSE_1_0.txt or copy at |
| 4 | * http://www.boost.org/LICENSE_1_0.txt) |
| 5 | * |
| 6 | * See https://www.boost.org/libs/unordered for library home page. |
| 7 | */ |
| 8 | |
| 9 | #ifndef BOOST_UNORDERED_DETAIL_NARROW_CAST_HPP |
| 10 | #define BOOST_UNORDERED_DETAIL_NARROW_CAST_HPP |
| 11 | |
| 12 | #include <boost/config.hpp> |
| 13 | #include <boost/static_assert.hpp> |
| 14 | #include <boost/type_traits/is_integral.hpp> |
| 15 | #include <boost/type_traits/make_unsigned.hpp> |
| 16 | |
| 17 | namespace boost{ |
| 18 | namespace unordered{ |
| 19 | namespace detail{ |
| 20 | |
| 21 | template<typename To,typename From> |
| 22 | BOOST_CONSTEXPR To narrow_cast(From x) BOOST_NOEXCEPT |
| 23 | { |
| 24 | BOOST_STATIC_ASSERT(boost::is_integral<From>::value); |
| 25 | BOOST_STATIC_ASSERT(boost::is_integral<To>::value); |
| 26 | BOOST_STATIC_ASSERT(sizeof(From)>=sizeof(To)); |
| 27 | |
| 28 | return static_cast<To>( |
| 29 | x |
| 30 | |
| 31 | #if defined(__MSVC_RUNTIME_CHECKS) |
| 32 | /* Avoids VS's "Run-Time Check Failure #1 - A cast to a smaller data type |
| 33 | * has caused a loss of data." |
| 34 | */ |
| 35 | &static_cast<typename boost::make_unsigned<To>::type>(~static_cast<To>(0)) |
| 36 | #endif |
| 37 | ); |
| 38 | } |
| 39 | |
| 40 | } /* namespace detail */ |
| 41 | } /* namespace unordered */ |
| 42 | } /* namespace boost */ |
| 43 | |
| 44 | #endif |
| 45 |