/src/abseil-cpp/absl/base/casts.h
Line | Count | Source |
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 | | |
24 | | #ifndef ABSL_BASE_CASTS_H_ |
25 | | #define ABSL_BASE_CASTS_H_ |
26 | | |
27 | | #include <cstring> |
28 | | #include <memory> |
29 | | #include <type_traits> |
30 | | #include <typeinfo> |
31 | | #include <utility> |
32 | | |
33 | | #ifdef __has_include |
34 | | #if __has_include(<version>) |
35 | | #include <version> // For __cpp_lib_bit_cast. |
36 | | #endif |
37 | | #endif |
38 | | |
39 | | #if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L |
40 | | #include <bit> // For std::bit_cast. |
41 | | #endif // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L |
42 | | |
43 | | #include "absl/base/attributes.h" |
44 | | #include "absl/base/config.h" |
45 | | #include "absl/base/macros.h" |
46 | | #include "absl/base/optimization.h" |
47 | | #include "absl/base/options.h" |
48 | | #include "absl/meta/type_traits.h" |
49 | | |
50 | | namespace absl { |
51 | | ABSL_NAMESPACE_BEGIN |
52 | | |
53 | | // implicit_cast() |
54 | | // |
55 | | // Performs an implicit conversion between types following the language |
56 | | // rules for implicit conversion; if an implicit conversion is otherwise |
57 | | // allowed by the language in the given context, this function performs such an |
58 | | // implicit conversion. |
59 | | // |
60 | | // Example: |
61 | | // |
62 | | // // If the context allows implicit conversion: |
63 | | // From from; |
64 | | // To to = from; |
65 | | // |
66 | | // // Such code can be replaced by: |
67 | | // implicit_cast<To>(from); |
68 | | // |
69 | | // An `implicit_cast()` may also be used to annotate numeric type conversions |
70 | | // that, although safe, may produce compiler warnings (such as `long` to `int`). |
71 | | // Additionally, an `implicit_cast()` is also useful within return statements to |
72 | | // indicate a specific implicit conversion is being undertaken. |
73 | | // |
74 | | // Example: |
75 | | // |
76 | | // return implicit_cast<double>(size_in_bytes) / capacity_; |
77 | | // |
78 | | // Annotating code with `implicit_cast()` allows you to explicitly select |
79 | | // particular overloads and template instantiations, while providing a safer |
80 | | // cast than `reinterpret_cast()` or `static_cast()`. |
81 | | // |
82 | | // Additionally, an `implicit_cast()` can be used to allow upcasting within a |
83 | | // type hierarchy where incorrect use of `static_cast()` could accidentally |
84 | | // allow downcasting. |
85 | | // |
86 | | // Finally, an `implicit_cast()` can be used to perform implicit conversions |
87 | | // from unrelated types that otherwise couldn't be implicitly cast directly; |
88 | | // C++ will normally only implicitly cast "one step" in such conversions. |
89 | | // |
90 | | // That is, if C is a type which can be implicitly converted to B, with B being |
91 | | // a type that can be implicitly converted to A, an `implicit_cast()` can be |
92 | | // used to convert C to B (which the compiler can then implicitly convert to A |
93 | | // using language rules). |
94 | | // |
95 | | // Example: |
96 | | // |
97 | | // // Assume an object C is convertible to B, which is implicitly convertible |
98 | | // // to A |
99 | | // A a = implicit_cast<B>(C); |
100 | | // |
101 | | // Such implicit cast chaining may be useful within template logic. |
102 | | template <typename To> |
103 | | constexpr std::enable_if_t< |
104 | | !type_traits_internal::IsView<std::enable_if_t< |
105 | | !std::is_reference_v<To>, std::remove_cv_t<To>>>::value, |
106 | | To> |
107 | | implicit_cast(absl::type_identity_t<To> to) { |
108 | | return to; |
109 | | } |
110 | | template <typename To> |
111 | | constexpr std::enable_if_t< |
112 | | type_traits_internal::IsView<std::enable_if_t<!std::is_reference_v<To>, |
113 | | std::remove_cv_t<To>>>::value, |
114 | | To> |
115 | | implicit_cast(absl::type_identity_t<To> to ABSL_ATTRIBUTE_LIFETIME_BOUND) { |
116 | | return to; |
117 | | } |
118 | | template <typename To> |
119 | | constexpr std::enable_if_t<std::is_reference_v<To>, To> implicit_cast( |
120 | | absl::type_identity_t<To> to ABSL_ATTRIBUTE_LIFETIME_BOUND) { |
121 | | return std::forward<absl::type_identity_t<To>>(to); |
122 | | } |
123 | | |
124 | | // bit_cast() |
125 | | // |
126 | | // Creates a value of the new type `Dest` whose representation is the same as |
127 | | // that of the argument, which is of (deduced) type `Source` (a "bitwise cast"; |
128 | | // every bit in the value representation of the result is equal to the |
129 | | // corresponding bit in the object representation of the source). Source and |
130 | | // destination types must be of the same size, and both types must be trivially |
131 | | // copyable. |
132 | | // |
133 | | // As with most casts, use with caution. A `bit_cast()` might be needed when you |
134 | | // need to treat a value as the value of some other type, for example, to access |
135 | | // the individual bits of an object which are not normally accessible through |
136 | | // the object's type, such as for working with the binary representation of a |
137 | | // floating point value: |
138 | | // |
139 | | // float f = 3.14159265358979; |
140 | | // int i = bit_cast<int>(f); |
141 | | // // i = 0x40490fdb |
142 | | // |
143 | | // Reinterpreting and accessing a value directly as a different type (as shown |
144 | | // below) usually results in undefined behavior. |
145 | | // |
146 | | // Example: |
147 | | // |
148 | | // // WRONG |
149 | | // float f = 3.14159265358979; |
150 | | // int i = reinterpret_cast<int&>(f); // Wrong |
151 | | // int j = *reinterpret_cast<int*>(&f); // Equally wrong |
152 | | // int k = *bit_cast<int*>(&f); // Equally wrong |
153 | | // |
154 | | // Reinterpret-casting results in undefined behavior according to the ISO C++ |
155 | | // specification, section [basic.lval]. Roughly, this section says: if an object |
156 | | // in memory has one type, and a program accesses it with a different type, the |
157 | | // result is undefined behavior for most "different type". |
158 | | // |
159 | | // Using bit_cast on a pointer and then dereferencing it is no better than using |
160 | | // reinterpret_cast. You should only use bit_cast on the value itself. |
161 | | // |
162 | | // Such casting results in type punning: holding an object in memory of one type |
163 | | // and reading its bits back using a different type. A `bit_cast()` avoids this |
164 | | // issue by copying the object representation to a new value, which avoids |
165 | | // introducing this undefined behavior (since the original value is never |
166 | | // accessed in the wrong way). |
167 | | // |
168 | | // The requirements of `absl::bit_cast` are more strict than that of |
169 | | // `std::bit_cast` unless compiler support is available. Specifically, without |
170 | | // compiler support, this implementation also requires `Dest` to be |
171 | | // default-constructible. In C++20, `absl::bit_cast` is replaced by |
172 | | // `std::bit_cast`. |
173 | | #if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L |
174 | | |
175 | | using std::bit_cast; |
176 | | |
177 | | #else // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L |
178 | | |
179 | | template < |
180 | | typename Dest, typename Source, |
181 | | typename std::enable_if<sizeof(Dest) == sizeof(Source) && |
182 | | std::is_trivially_copyable<Source>::value && |
183 | | std::is_trivially_copyable<Dest>::value |
184 | | #if !ABSL_HAVE_BUILTIN(__builtin_bit_cast) |
185 | | && std::is_default_constructible<Dest>::value |
186 | | #endif // !ABSL_HAVE_BUILTIN(__builtin_bit_cast) |
187 | | , |
188 | | int>::type = 0> |
189 | | #if ABSL_HAVE_BUILTIN(__builtin_bit_cast) |
190 | 0 | inline constexpr Dest bit_cast(const Source& source) { |
191 | 0 | return __builtin_bit_cast(Dest, source); |
192 | 0 | } Unexecuted instantiation: _ZN4absl8bit_castImdTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ Unexecuted instantiation: _ZN4absl8bit_castIjfTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ Unexecuted instantiation: _ZN4absl8bit_castIdmTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ Unexecuted instantiation: _ZN4absl8bit_castIfjTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ Unexecuted instantiation: _ZN4absl8bit_castItsTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ Unexecuted instantiation: _ZN4absl8bit_castIstTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ Unexecuted instantiation: _ZN4absl8bit_castIjiTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ Unexecuted instantiation: _ZN4absl8bit_castIijTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ Unexecuted instantiation: _ZN4absl8bit_castImlTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ Unexecuted instantiation: _ZN4absl8bit_castIlmTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3std21is_trivially_copyableIS4_EE5valuesr3std21is_trivially_copyableIS3_EE5valueEiE4typeELi0EEES3_RKS4_ |
193 | | #else // ABSL_HAVE_BUILTIN(__builtin_bit_cast) |
194 | | inline Dest bit_cast(const Source& source) { |
195 | | Dest dest; |
196 | | memcpy(static_cast<void*>(std::addressof(dest)), |
197 | | static_cast<const void*>(std::addressof(source)), sizeof(dest)); |
198 | | return dest; |
199 | | } |
200 | | #endif // ABSL_HAVE_BUILTIN(__builtin_bit_cast) |
201 | | |
202 | | #endif // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L |
203 | | |
204 | | namespace base_internal { |
205 | | |
206 | | [[noreturn]] ABSL_ATTRIBUTE_NOINLINE void BadDownCastCrash( |
207 | | const char* source_type, const char* target_type); |
208 | | |
209 | | template <typename To, typename From> |
210 | | inline void ValidateDownCast(From* f ABSL_ATTRIBUTE_UNUSED) { |
211 | | // Assert only if RTTI is enabled and in debug mode or hardened asserts are |
212 | | // enabled. |
213 | | #ifdef ABSL_INTERNAL_HAS_RTTI |
214 | | #if !defined(NDEBUG) || (ABSL_OPTION_HARDENED == 1) |
215 | | // Suppress erroneous nonnull comparison warning on older GCC. |
216 | | #if defined(__GNUC__) && !defined(__clang__) |
217 | | #pragma GCC diagnostic push |
218 | | #pragma GCC diagnostic ignored "-Wnonnull-compare" |
219 | | #endif |
220 | | if (ABSL_PREDICT_FALSE(f != nullptr && dynamic_cast<To>(f) == nullptr)) { |
221 | | #if defined(__GNUC__) && !defined(__clang__) |
222 | | #pragma GCC diagnostic pop |
223 | | #endif |
224 | | absl::base_internal::BadDownCastCrash( |
225 | | typeid(*f).name(), typeid(std::remove_pointer_t<To>).name()); |
226 | | } |
227 | | #endif |
228 | | #endif |
229 | | } |
230 | | |
231 | | } // namespace base_internal |
232 | | |
233 | | // An "upcast", i.e. a conversion from a pointer to an object to a pointer to a |
234 | | // base subobject, always succeeds if the base is unambiguous and accessible, |
235 | | // and so it's fine to use implicit_cast. |
236 | | // |
237 | | // A "downcast", i.e. a conversion from a pointer to an object to a pointer |
238 | | // to a more-derived object that may contain the original object as a base |
239 | | // subobject, cannot safely be done using static_cast, because you do not |
240 | | // generally know whether the source object is really the base subobject of |
241 | | // a containing, more-derived object of the target type. Thus, when you |
242 | | // downcast in a polymorphic type hierarchy, you should use the following |
243 | | // function template. |
244 | | // |
245 | | // This function only returns null when the input is null. In debug mode, we |
246 | | // use dynamic_cast to double-check whether the downcast is legal (we die if |
247 | | // it's not). In normal mode, we do the efficient static_cast instead. Because |
248 | | // the process will die in debug mode, it's important to test to make sure the |
249 | | // cast is legal before calling this function! |
250 | | // |
251 | | // dynamic_cast should be avoided except as allowed by the style guide |
252 | | // (https://google.github.io/styleguide/cppguide.html#Run-Time_Type_Information__RTTI_). |
253 | | |
254 | | template <typename To, typename From> // use like this: down_cast<T*>(foo); |
255 | | [[nodiscard]] |
256 | | inline To down_cast(From* f) { // so we only accept pointers |
257 | | static_assert(std::is_pointer<To>::value, "target type not a pointer"); |
258 | | // dynamic_cast allows casting to the same type or a more cv-qualified |
259 | | // version of the same type without them being polymorphic. |
260 | | if constexpr (!std::is_same<std::remove_cv_t<std::remove_pointer_t<To>>, |
261 | | std::remove_cv_t<From>>::value) { |
262 | | static_assert(std::is_polymorphic<From>::value, |
263 | | "source type must be polymorphic"); |
264 | | static_assert(std::is_polymorphic<std::remove_pointer_t<To>>::value, |
265 | | "target type must be polymorphic"); |
266 | | } |
267 | | static_assert( |
268 | | std::is_convertible<std::remove_cv_t<std::remove_pointer_t<To>>*, |
269 | | std::remove_cv_t<From>*>::value, |
270 | | "target type not derived from source type"); |
271 | | |
272 | | absl::base_internal::ValidateDownCast<To>(f); |
273 | | |
274 | | return static_cast<To>(f); |
275 | | } |
276 | | |
277 | | // Overload of down_cast for references. Use like this: |
278 | | // absl::down_cast<T&>(foo). The code is slightly convoluted because we're still |
279 | | // using the pointer form of dynamic cast. (The reference form throws an |
280 | | // exception if it fails.) |
281 | | // |
282 | | // There's no need for a special const overload either for the pointer |
283 | | // or the reference form. If you call down_cast with a const T&, the |
284 | | // compiler will just bind From to const T. |
285 | | template <typename To, typename From> |
286 | | [[nodiscard]] |
287 | | inline To down_cast(From& f) { |
288 | | static_assert(std::is_lvalue_reference<To>::value, |
289 | | "target type not a reference"); |
290 | | // dynamic_cast allows casting to the same type or a more cv-qualified |
291 | | // version of the same type without them being polymorphic. |
292 | | if constexpr (!std::is_same<std::remove_cv_t<std::remove_reference_t<To>>, |
293 | | std::remove_cv_t<From>>::value) { |
294 | | static_assert(std::is_polymorphic<From>::value, |
295 | | "source type must be polymorphic"); |
296 | | static_assert(std::is_polymorphic<std::remove_reference_t<To>>::value, |
297 | | "target type must be polymorphic"); |
298 | | } |
299 | | static_assert( |
300 | | std::is_convertible<std::remove_cv_t<std::remove_reference_t<To>>*, |
301 | | std::remove_cv_t<From>*>::value, |
302 | | "target type not derived from source type"); |
303 | | |
304 | | absl::base_internal::ValidateDownCast<std::remove_reference_t<To>*>( |
305 | | std::addressof(f)); |
306 | | |
307 | | return static_cast<To>(f); |
308 | | } |
309 | | |
310 | | ABSL_NAMESPACE_END |
311 | | } // namespace absl |
312 | | |
313 | | #endif // ABSL_BASE_CASTS_H_ |