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