bit_cast.hpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #ifndef BOOST_HASH2_DETAIL_BIT_CAST_HPP_INCLUDED
  2. #define BOOST_HASH2_DETAIL_BIT_CAST_HPP_INCLUDED
  3. // Copyright 2024 Peter Dimov
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // https://www.boost.org/LICENSE_1_0.txt
  6. #include <boost/hash2/detail/config.hpp>
  7. #include <boost/config.hpp>
  8. #include <type_traits>
  9. #include <cstring>
  10. namespace boost
  11. {
  12. namespace hash2
  13. {
  14. namespace detail
  15. {
  16. template<class To, class From> BOOST_CXX14_CONSTEXPR To bit_cast( From const& from ) noexcept
  17. {
  18. static_assert( sizeof(From) == sizeof(To), "Types must be the same size" );
  19. #if defined(BOOST_LIBSTDCXX_VERSION) && BOOST_LIBSTDCXX_VERSION < 50000
  20. // std::is_trivially_copyable doesn't exist in libstdc++ 4.x
  21. #else
  22. static_assert( std::is_trivially_copyable<From>::value, "Types must be trivially copyable" );
  23. static_assert( std::is_trivially_copyable<To>::value, "Types must be trivially copyable" );
  24. #endif
  25. #if defined(BOOST_HASH2_HAS_BUILTIN_BIT_CAST)
  26. return __builtin_bit_cast( To, from );
  27. #else
  28. To to{};
  29. std::memcpy( &to, &from, sizeof(From) );
  30. return to;
  31. #endif
  32. }
  33. } // namespace detail
  34. } // namespace hash2
  35. } // namespace boost
  36. #endif // #ifndef BOOST_HASH2_DETAIL_BIT_CAST_HPP_INCLUDED