Nugget
bit.h
1 // Copyright (c) Electronic Arts Inc. All rights reserved.
4 
5 #ifndef EASTL_BIT_H
6 #define EASTL_BIT_H
7 
8 #include <EASTL/internal/config.h>
9 
10 #if defined(EA_PRAGMA_ONCE_SUPPORTED)
11  #pragma once
12 #endif
13 
14 #include <EASTL/internal/memory_base.h>
15 #include <EASTL/type_traits.h>
16 #include <string.h> // memcpy
17 
18 namespace eastl
19 {
20  // eastl::bit_cast
21  // Obtains a value of type To by reinterpreting the object representation of 'from'.
22  // Every bit in the value representation of the returned To object is equal to the
23  // corresponding bit in the object representation of 'from'.
24  //
25  // In order for bit_cast to be constexpr, the compiler needs to explicitly support
26  // it by providing the __builtin_bit_cast builtin. If that builtin is not available,
27  // then we memcpy into aligned storage at runtime and return that instead.
28  //
29  // Both types To and From must be equal in size, and must be trivially copyable.
30 
31  #if defined(EASTL_CONSTEXPR_BIT_CAST_SUPPORTED) && EASTL_CONSTEXPR_BIT_CAST_SUPPORTED
32 
33  template<typename To, typename From,
34  typename = eastl::enable_if_t<
35  sizeof(To) == sizeof(From)
38  >
39  >
40  EA_CONSTEXPR To bit_cast(const From& from) EA_NOEXCEPT
41  {
42  return __builtin_bit_cast(To, from);
43  }
44 
45  #else
46 
47  template<typename To, typename From,
48  typename = eastl::enable_if_t<
49  sizeof(To) == sizeof(From)
52  >
53  >
54  inline To bit_cast(const From& from) EA_NOEXCEPT
55  {
56  typename eastl::aligned_storage<sizeof(To), alignof(To)>::type to;
57  ::memcpy(eastl::addressof(to), eastl::addressof(from), sizeof(To));
58  return reinterpret_cast<To&>(to);
59  }
60 
61  #endif // EASTL_CONSTEXPR_BIT_CAST_SUPPORTED
62 
63 } // namespace eastl
64 
65 #endif // EASTL_BIT_H
EA Standard Template Library.
Definition: algorithm.h:288
T * addressof(T &value) EA_NOEXCEPT
Definition: memory_base.h:29
Definition: type_transformations.h:615
Definition: type_pod.h:708