xref: /aosp_15_r20/external/pytorch/c10/util/bit_cast.h (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1*da0073e9SAndroid Build Coastguard Worker #pragma once
2*da0073e9SAndroid Build Coastguard Worker 
3*da0073e9SAndroid Build Coastguard Worker #include <cstring>
4*da0073e9SAndroid Build Coastguard Worker #include <type_traits>
5*da0073e9SAndroid Build Coastguard Worker 
6*da0073e9SAndroid Build Coastguard Worker namespace c10 {
7*da0073e9SAndroid Build Coastguard Worker 
8*da0073e9SAndroid Build Coastguard Worker // Implementations of std::bit_cast() from C++ 20.
9*da0073e9SAndroid Build Coastguard Worker //
10*da0073e9SAndroid Build Coastguard Worker // This is a less sketchy version of reinterpret_cast.
11*da0073e9SAndroid Build Coastguard Worker //
12*da0073e9SAndroid Build Coastguard Worker // See https://en.cppreference.com/w/cpp/numeric/bit_cast for more
13*da0073e9SAndroid Build Coastguard Worker // information as well as the source of our implementations.
14*da0073e9SAndroid Build Coastguard Worker template <class To, class From>
15*da0073e9SAndroid Build Coastguard Worker std::enable_if_t<
16*da0073e9SAndroid Build Coastguard Worker     sizeof(To) == sizeof(From) && std::is_trivially_copyable_v<From> &&
17*da0073e9SAndroid Build Coastguard Worker         std::is_trivially_copyable_v<To>,
18*da0073e9SAndroid Build Coastguard Worker     To>
19*da0073e9SAndroid Build Coastguard Worker // constexpr support needs compiler magic
bit_cast(const From & src)20*da0073e9SAndroid Build Coastguard Worker bit_cast(const From& src) noexcept {
21*da0073e9SAndroid Build Coastguard Worker   static_assert(
22*da0073e9SAndroid Build Coastguard Worker       std::is_trivially_constructible_v<To>,
23*da0073e9SAndroid Build Coastguard Worker       "This implementation additionally requires "
24*da0073e9SAndroid Build Coastguard Worker       "destination type to be trivially constructible");
25*da0073e9SAndroid Build Coastguard Worker 
26*da0073e9SAndroid Build Coastguard Worker   To dst;
27*da0073e9SAndroid Build Coastguard Worker   std::memcpy(&dst, &src, sizeof(To));
28*da0073e9SAndroid Build Coastguard Worker   return dst;
29*da0073e9SAndroid Build Coastguard Worker }
30*da0073e9SAndroid Build Coastguard Worker 
31*da0073e9SAndroid Build Coastguard Worker } // namespace c10
32