bit_cast.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #ifndef _LIBCPP___BIT_BIT_CAST_H
  10. #define _LIBCPP___BIT_BIT_CAST_H
  11. #include <__config>
  12. #include <cstring>
  13. #include <type_traits>
  14. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  15. # pragma GCC system_header
  16. #endif
  17. _LIBCPP_BEGIN_NAMESPACE_STD
  18. #if _LIBCPP_STD_VER > 17
  19. template<class _ToType, class _FromType, class = enable_if_t<
  20. sizeof(_ToType) == sizeof(_FromType) &&
  21. is_trivially_copyable_v<_ToType> &&
  22. is_trivially_copyable_v<_FromType>
  23. >>
  24. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI
  25. constexpr _ToType bit_cast(_FromType const& __from) noexcept {
  26. return __builtin_bit_cast(_ToType, __from);
  27. }
  28. #else _LIBCPP_STD_VER > 14
  29. template<class _ToType, class _FromType, class = enable_if_t<
  30. sizeof(_ToType) == sizeof(_FromType) &&
  31. is_trivially_copyable<_ToType>::value &&
  32. is_trivially_copyable<_FromType>::value
  33. >>
  34. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI
  35. constexpr _ToType bit_cast(_FromType const& __from) noexcept {
  36. _ToType __to;
  37. ::memcpy(&__to, &__from, sizeof(__from));
  38. return __to;
  39. }
  40. #endif // _LIBCPP_STD_VER > 17
  41. _LIBCPP_END_NAMESPACE_STD
  42. #endif // _LIBCPP___BIT_BIT_CAST_H