casts.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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 ABSL_BASE_CASTS_H_
  24. #define ABSL_BASE_CASTS_H_
  25. #include <cstring>
  26. #include <memory>
  27. #include <type_traits>
  28. #include <utility>
  29. #include "absl/base/internal/identity.h"
  30. #include "absl/base/macros.h"
  31. #include "absl/meta/type_traits.h"
  32. namespace absl {
  33. ABSL_NAMESPACE_BEGIN
  34. namespace internal_casts {
  35. template <class Dest, class Source>
  36. struct is_bitcastable
  37. : std::integral_constant<
  38. bool,
  39. sizeof(Dest) == sizeof(Source) &&
  40. type_traits_internal::is_trivially_copyable<Source>::value &&
  41. type_traits_internal::is_trivially_copyable<Dest>::value &&
  42. std::is_default_constructible<Dest>::value> {};
  43. } // namespace internal_casts
  44. // implicit_cast()
  45. //
  46. // Performs an implicit conversion between types following the language
  47. // rules for implicit conversion; if an implicit conversion is otherwise
  48. // allowed by the language in the given context, this function performs such an
  49. // implicit conversion.
  50. //
  51. // Example:
  52. //
  53. // // If the context allows implicit conversion:
  54. // From from;
  55. // To to = from;
  56. //
  57. // // Such code can be replaced by:
  58. // implicit_cast<To>(from);
  59. //
  60. // An `implicit_cast()` may also be used to annotate numeric type conversions
  61. // that, although safe, may produce compiler warnings (such as `long` to `int`).
  62. // Additionally, an `implicit_cast()` is also useful within return statements to
  63. // indicate a specific implicit conversion is being undertaken.
  64. //
  65. // Example:
  66. //
  67. // return implicit_cast<double>(size_in_bytes) / capacity_;
  68. //
  69. // Annotating code with `implicit_cast()` allows you to explicitly select
  70. // particular overloads and template instantiations, while providing a safer
  71. // cast than `reinterpret_cast()` or `static_cast()`.
  72. //
  73. // Additionally, an `implicit_cast()` can be used to allow upcasting within a
  74. // type hierarchy where incorrect use of `static_cast()` could accidentally
  75. // allow downcasting.
  76. //
  77. // Finally, an `implicit_cast()` can be used to perform implicit conversions
  78. // from unrelated types that otherwise couldn't be implicitly cast directly;
  79. // C++ will normally only implicitly cast "one step" in such conversions.
  80. //
  81. // That is, if C is a type which can be implicitly converted to B, with B being
  82. // a type that can be implicitly converted to A, an `implicit_cast()` can be
  83. // used to convert C to B (which the compiler can then implicitly convert to A
  84. // using language rules).
  85. //
  86. // Example:
  87. //
  88. // // Assume an object C is convertible to B, which is implicitly convertible
  89. // // to A
  90. // A a = implicit_cast<B>(C);
  91. //
  92. // Such implicit cast chaining may be useful within template logic.
  93. template <typename To>
  94. constexpr To implicit_cast(typename absl::internal::identity_t<To> to) {
  95. return to;
  96. }
  97. // bit_cast()
  98. //
  99. // Performs a bitwise cast on a type without changing the underlying bit
  100. // representation of that type's value. The two types must be of the same size
  101. // and both types must be trivially copyable. As with most casts, use with
  102. // caution. A `bit_cast()` might be needed when you need to temporarily treat a
  103. // type as some other type, such as in the following cases:
  104. //
  105. // * Serialization (casting temporarily to `char *` for those purposes is
  106. // always allowed by the C++ standard)
  107. // * Managing the individual bits of a type within mathematical operations
  108. // that are not normally accessible through that type
  109. // * Casting non-pointer types to pointer types (casting the other way is
  110. // allowed by `reinterpret_cast()` but round-trips cannot occur the other
  111. // way).
  112. //
  113. // Example:
  114. //
  115. // float f = 3.14159265358979;
  116. // int i = bit_cast<int32_t>(f);
  117. // // i = 0x40490fdb
  118. //
  119. // Casting non-pointer types to pointer types and then dereferencing them
  120. // traditionally produces undefined behavior.
  121. //
  122. // Example:
  123. //
  124. // // WRONG
  125. // float f = 3.14159265358979; // WRONG
  126. // int i = * reinterpret_cast<int*>(&f); // WRONG
  127. //
  128. // The address-casting method produces undefined behavior according to the ISO
  129. // C++ specification section [basic.lval]. Roughly, this section says: if an
  130. // object in memory has one type, and a program accesses it with a different
  131. // type, the result is undefined behavior for most values of "different type".
  132. //
  133. // Such casting results in type punning: holding an object in memory of one type
  134. // and reading its bits back using a different type. A `bit_cast()` avoids this
  135. // issue by implementing its casts using `memcpy()`, which avoids introducing
  136. // this undefined behavior.
  137. //
  138. // NOTE: The requirements here are more strict than the bit_cast of standard
  139. // proposal p0476 due to the need for workarounds and lack of intrinsics.
  140. // Specifically, this implementation also requires `Dest` to be
  141. // default-constructible.
  142. template <
  143. typename Dest, typename Source,
  144. typename std::enable_if<internal_casts::is_bitcastable<Dest, Source>::value,
  145. int>::type = 0>
  146. inline Dest bit_cast(const Source& source) {
  147. Dest dest;
  148. memcpy(static_cast<void*>(std::addressof(dest)),
  149. static_cast<const void*>(std::addressof(source)), sizeof(dest));
  150. return dest;
  151. }
  152. // NOTE: This overload is only picked if the requirements of bit_cast are
  153. // not met. It is therefore UB, but is provided temporarily as previous
  154. // versions of this function template were unchecked. Do not use this in
  155. // new code.
  156. template <
  157. typename Dest, typename Source,
  158. typename std::enable_if<
  159. !internal_casts::is_bitcastable<Dest, Source>::value,
  160. int>::type = 0>
  161. ABSL_DEPRECATED(
  162. "absl::bit_cast type requirements were violated. Update the types "
  163. "being used such that they are the same size and are both "
  164. "TriviallyCopyable.")
  165. inline Dest bit_cast(const Source& source) {
  166. static_assert(sizeof(Dest) == sizeof(Source),
  167. "Source and destination types should have equal sizes.");
  168. Dest dest;
  169. memcpy(&dest, &source, sizeof(dest));
  170. return dest;
  171. }
  172. ABSL_NAMESPACE_END
  173. } // namespace absl
  174. #endif // ABSL_BASE_CASTS_H_