Skip to content

Commit

Permalink
Update edm::bit_cast
Browse files Browse the repository at this point in the history
Use std::bit_cast in C++20 mode, or __builtin_bit_cast if available, otherwise
fall back to memcpy.
  • Loading branch information
fwyzard committed Jun 9, 2024
1 parent 695ed78 commit c619df6
Showing 1 changed file with 32 additions and 8 deletions.
40 changes: 32 additions & 8 deletions FWCore/Utilities/interface/bit_cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,43 @@
// Created: Wed, 01 Sep 2021 19:11:41 GMT
//

// for compilers that do not support __has_builtin
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif

// system include files
#include <cstring>
#include <type_traits>

#if __cplusplus >= 202002L

// in C++20 we can use std::bit_cast

#include <bit>

namespace edm {
using std::bit_cast;
} // namespace edm

#elif __has_builtin(__builtin_bit_cast)

// user include files
// before C++20 we can use __builtin_bit_cast, if supported

namespace edm {
//in C++20 we can use std::bit_cast which is constexpr
template <class To, class From>
inline To bit_cast(const From &src) noexcept {
template <typename To, typename From>
constexpr inline To bit_cast(const From &src) noexcept {
static_assert(std::is_trivially_copyable_v<From>);
static_assert(std::is_trivially_copyable_v<To>);
static_assert(sizeof(To) == sizeof(From), "incompatible types");
To dst;
std::memcpy(&dst, &src, sizeof(To));
return dst;
return __builtin_bit_cast(To, src);
}
} // namespace edm
#endif

#else

#error constexpr edm::bit_cast is not supported by the compiler

#endif // __cplusplus >= 202002L

#endif // FWCore_Utilities_bit_cast_h

0 comments on commit c619df6

Please sign in to comment.