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