casts.h 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. //
  2. // Copyright 2017 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. // -----------------------------------------------------------------------------
  17. // File: casts.h
  18. // -----------------------------------------------------------------------------
  19. //
  20. // This header file defines casting templates to fit use cases not covered by
  21. // the standard casts provided in the C++ standard. As with all cast operations,
  22. // use these with caution and only if alternatives do not exist.
  23. #ifndef Y_ABSL_BASE_CASTS_H_
  24. #define Y_ABSL_BASE_CASTS_H_
  25. #include <cstring>
  26. #include <memory>
  27. #include <type_traits>
  28. #include <utility>
  29. #if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
  30. #include <bit> // For std::bit_cast.
  31. #endif // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
  32. #include "y_absl/base/internal/identity.h"
  33. #include "y_absl/base/macros.h"
  34. #include "y_absl/meta/type_traits.h"
  35. namespace y_absl {
  36. Y_ABSL_NAMESPACE_BEGIN
  37. // implicit_cast()
  38. //
  39. // Performs an implicit conversion between types following the language
  40. // rules for implicit conversion; if an implicit conversion is otherwise
  41. // allowed by the language in the given context, this function performs such an
  42. // implicit conversion.
  43. //
  44. // Example:
  45. //
  46. // // If the context allows implicit conversion:
  47. // From from;
  48. // To to = from;
  49. //
  50. // // Such code can be replaced by:
  51. // implicit_cast<To>(from);
  52. //
  53. // An `implicit_cast()` may also be used to annotate numeric type conversions
  54. // that, although safe, may produce compiler warnings (such as `long` to `int`).
  55. // Additionally, an `implicit_cast()` is also useful within return statements to
  56. // indicate a specific implicit conversion is being undertaken.
  57. //
  58. // Example:
  59. //
  60. // return implicit_cast<double>(size_in_bytes) / capacity_;
  61. //
  62. // Annotating code with `implicit_cast()` allows you to explicitly select
  63. // particular overloads and template instantiations, while providing a safer
  64. // cast than `reinterpret_cast()` or `static_cast()`.
  65. //
  66. // Additionally, an `implicit_cast()` can be used to allow upcasting within a
  67. // type hierarchy where incorrect use of `static_cast()` could accidentally
  68. // allow downcasting.
  69. //
  70. // Finally, an `implicit_cast()` can be used to perform implicit conversions
  71. // from unrelated types that otherwise couldn't be implicitly cast directly;
  72. // C++ will normally only implicitly cast "one step" in such conversions.
  73. //
  74. // That is, if C is a type which can be implicitly converted to B, with B being
  75. // a type that can be implicitly converted to A, an `implicit_cast()` can be
  76. // used to convert C to B (which the compiler can then implicitly convert to A
  77. // using language rules).
  78. //
  79. // Example:
  80. //
  81. // // Assume an object C is convertible to B, which is implicitly convertible
  82. // // to A
  83. // A a = implicit_cast<B>(C);
  84. //
  85. // Such implicit cast chaining may be useful within template logic.
  86. template <typename To>
  87. constexpr To implicit_cast(typename y_absl::internal::identity_t<To> to) {
  88. return to;
  89. }
  90. // bit_cast()
  91. //
  92. // Creates a value of the new type `Dest` whose representation is the same as
  93. // that of the argument, which is of (deduced) type `Source` (a "bitwise cast";
  94. // every bit in the value representation of the result is equal to the
  95. // corresponding bit in the object representation of the source). Source and
  96. // destination types must be of the same size, and both types must be trivially
  97. // copyable.
  98. //
  99. // As with most casts, use with caution. A `bit_cast()` might be needed when you
  100. // need to treat a value as the value of some other type, for example, to access
  101. // the individual bits of an object which are not normally accessible through
  102. // the object's type, such as for working with the binary representation of a
  103. // floating point value:
  104. //
  105. // float f = 3.14159265358979;
  106. // int i = bit_cast<int>(f);
  107. // // i = 0x40490fdb
  108. //
  109. // Reinterpreting and accessing a value directly as a different type (as shown
  110. // below) usually results in undefined behavior.
  111. //
  112. // Example:
  113. //
  114. // // WRONG
  115. // float f = 3.14159265358979;
  116. // int i = reinterpret_cast<int&>(f); // Wrong
  117. // int j = *reinterpret_cast<int*>(&f); // Equally wrong
  118. // int k = *bit_cast<int*>(&f); // Equally wrong
  119. //
  120. // Reinterpret-casting results in undefined behavior according to the ISO C++
  121. // specification, section [basic.lval]. Roughly, this section says: if an object
  122. // in memory has one type, and a program accesses it with a different type, the
  123. // result is undefined behavior for most "different type".
  124. //
  125. // Using bit_cast on a pointer and then dereferencing it is no better than using
  126. // reinterpret_cast. You should only use bit_cast on the value itself.
  127. //
  128. // Such casting results in type punning: holding an object in memory of one type
  129. // and reading its bits back using a different type. A `bit_cast()` avoids this
  130. // issue by copying the object representation to a new value, which avoids
  131. // introducing this undefined behavior (since the original value is never
  132. // accessed in the wrong way).
  133. //
  134. // The requirements of `y_absl::bit_cast` are more strict than that of
  135. // `std::bit_cast` unless compiler support is available. Specifically, without
  136. // compiler support, this implementation also requires `Dest` to be
  137. // default-constructible. In C++20, `y_absl::bit_cast` is replaced by
  138. // `std::bit_cast`.
  139. #if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
  140. using std::bit_cast;
  141. #else // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
  142. template <
  143. typename Dest, typename Source,
  144. typename std::enable_if<sizeof(Dest) == sizeof(Source) &&
  145. std::is_trivially_copyable<Source>::value &&
  146. std::is_trivially_copyable<Dest>::value
  147. #if !Y_ABSL_HAVE_BUILTIN(__builtin_bit_cast)
  148. && std::is_default_constructible<Dest>::value
  149. #endif // !Y_ABSL_HAVE_BUILTIN(__builtin_bit_cast)
  150. ,
  151. int>::type = 0>
  152. #if Y_ABSL_HAVE_BUILTIN(__builtin_bit_cast) && (!defined(__CUDACC__) || CUDA_VERSION >= 11010)
  153. inline constexpr Dest bit_cast(const Source& source) {
  154. return __builtin_bit_cast(Dest, source);
  155. }
  156. #else // Y_ABSL_HAVE_BUILTIN(__builtin_bit_cast)
  157. inline Dest bit_cast(const Source& source) {
  158. Dest dest;
  159. memcpy(static_cast<void*>(std::addressof(dest)),
  160. static_cast<const void*>(std::addressof(source)), sizeof(dest));
  161. return dest;
  162. }
  163. #endif // Y_ABSL_HAVE_BUILTIN(__builtin_bit_cast)
  164. #endif // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
  165. Y_ABSL_NAMESPACE_END
  166. } // namespace y_absl
  167. #endif // Y_ABSL_BASE_CASTS_H_