Coverage Report

Created: 2026-07-16 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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 <typename Dest, typename Source,
180
          std::enable_if_t<sizeof(Dest) == sizeof(Source) &&
181
                               std::is_trivially_copyable_v<Source> &&
182
                               std::is_trivially_copyable_v<Dest>
183
#if !ABSL_HAVE_BUILTIN(__builtin_bit_cast)
184
                               && std::is_default_constructible_v<Dest>
185
#endif  // !ABSL_HAVE_BUILTIN(__builtin_bit_cast)
186
                           ,
187
                           int> = 0>
188
#if ABSL_HAVE_BUILTIN(__builtin_bit_cast)
189
0
inline constexpr Dest bit_cast(const Source& source) {
190
0
  return __builtin_bit_cast(Dest, source);
191
0
}
Unexecuted instantiation: _ZN4absl8bit_castImdTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
Unexecuted instantiation: _ZN4absl8bit_castIjfTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
Unexecuted instantiation: _ZN4absl8bit_castIdmTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
Unexecuted instantiation: _ZN4absl8bit_castIfjTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
Unexecuted instantiation: _ZN4absl8bit_castItsTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
Unexecuted instantiation: _ZN4absl8bit_castIstTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
Unexecuted instantiation: _ZN4absl8bit_castIjiTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
Unexecuted instantiation: _ZN4absl8bit_castIijTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
Unexecuted instantiation: _ZN4absl8bit_castImlTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
Unexecuted instantiation: _ZN4absl8bit_castIlmTnNSt3__19enable_ifIXaaaaeqstT_stT0_sr3stdE23is_trivially_copyable_vIS4_Esr3stdE23is_trivially_copyable_vIS3_EEiE4typeELi0EEES3_RKS4_
192
#else  // ABSL_HAVE_BUILTIN(__builtin_bit_cast)
193
inline Dest bit_cast(const Source& source) {
194
  Dest dest;
195
  memcpy(static_cast<void*>(std::addressof(dest)),
196
         static_cast<const void*>(std::addressof(source)), sizeof(dest));
197
  return dest;
198
}
199
#endif  // ABSL_HAVE_BUILTIN(__builtin_bit_cast)
200
201
#endif  // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
202
203
namespace base_internal {
204
205
[[noreturn]] ABSL_ATTRIBUTE_NOINLINE void BadDownCastCrash(
206
    const char* source_type, const char* target_type);
207
208
template <typename To, typename From>
209
inline void ValidateDownCast(From* f ABSL_ATTRIBUTE_UNUSED) {
210
  // Assert only if RTTI is enabled and in debug mode or hardened asserts are
211
  // enabled.
212
#ifdef ABSL_INTERNAL_HAS_RTTI
213
#if !defined(NDEBUG) || (ABSL_OPTION_HARDENED == 1)
214
  // Suppress erroneous nonnull comparison warning on older GCC.
215
#if defined(__GNUC__) && !defined(__clang__)
216
#pragma GCC diagnostic push
217
#pragma GCC diagnostic ignored "-Wnonnull-compare"
218
#endif
219
  if (ABSL_PREDICT_FALSE(f != nullptr && dynamic_cast<To>(f) == nullptr)) {
220
#if defined(__GNUC__) && !defined(__clang__)
221
#pragma GCC diagnostic pop
222
#endif
223
    absl::base_internal::BadDownCastCrash(
224
        typeid(*f).name(), typeid(std::remove_pointer_t<To>).name());
225
  }
226
#endif
227
#endif
228
}
229
230
}  // namespace base_internal
231
232
// An "upcast", i.e. a conversion from a pointer to an object to a pointer to a
233
// base subobject, always succeeds if the base is unambiguous and accessible,
234
// and so it's fine to use implicit_cast.
235
//
236
// A "downcast", i.e. a conversion from a pointer to an object to a pointer
237
// to a more-derived object that may contain the original object as a base
238
// subobject, cannot safely be done using static_cast, because you do not
239
// generally know whether the source object is really the base subobject of
240
// a containing, more-derived object of the target type. Thus, when you
241
// downcast in a polymorphic type hierarchy, you should use the following
242
// function template.
243
//
244
// This function only returns null when the input is null. In debug mode, we
245
// use dynamic_cast to double-check whether the downcast is legal (we die if
246
// it's not). In normal mode, we do the efficient static_cast instead. Because
247
// the process will die in debug mode, it's important to test to make sure the
248
// cast is legal before calling this function!
249
//
250
// dynamic_cast should be avoided except as allowed by the style guide
251
// (https://google.github.io/styleguide/cppguide.html#Run-Time_Type_Information__RTTI_).
252
253
template <typename To, typename From>  // use like this: down_cast<T*>(foo);
254
[[nodiscard]]
255
inline To down_cast(From* f) {  // so we only accept pointers
256
  static_assert(std::is_pointer_v<To>, "target type not a pointer");
257
  // dynamic_cast allows casting to the same type or a more cv-qualified
258
  // version of the same type without them being polymorphic.
259
  if constexpr (!std::is_same_v<std::remove_cv_t<std::remove_pointer_t<To>>,
260
                                std::remove_cv_t<From>>) {
261
    static_assert(std::is_polymorphic_v<From>,
262
                  "source type must be polymorphic");
263
    static_assert(std::is_polymorphic_v<std::remove_pointer_t<To>>,
264
                  "target type must be polymorphic");
265
  }
266
  static_assert(
267
      std::is_convertible_v<std::remove_cv_t<std::remove_pointer_t<To>>*,
268
                            std::remove_cv_t<From>*>,
269
      "target type not derived from source type");
270
271
  absl::base_internal::ValidateDownCast<To>(f);
272
273
  return static_cast<To>(f);
274
}
275
276
// Overload of down_cast for references. Use like this:
277
// absl::down_cast<T&>(foo). The code is slightly convoluted because we're still
278
// using the pointer form of dynamic cast. (The reference form throws an
279
// exception if it fails.)
280
//
281
// There's no need for a special const overload either for the pointer
282
// or the reference form. If you call down_cast with a const T&, the
283
// compiler will just bind From to const T.
284
template <typename To, typename From>
285
[[nodiscard]]
286
inline To down_cast(From& f) {
287
  static_assert(std::is_lvalue_reference_v<To>, "target type not a reference");
288
  // dynamic_cast allows casting to the same type or a more cv-qualified
289
  // version of the same type without them being polymorphic.
290
  if constexpr (!std::is_same_v<std::remove_cv_t<std::remove_reference_t<To>>,
291
                                std::remove_cv_t<From>>) {
292
    static_assert(std::is_polymorphic_v<From>,
293
                  "source type must be polymorphic");
294
    static_assert(std::is_polymorphic_v<std::remove_reference_t<To>>,
295
                  "target type must be polymorphic");
296
  }
297
  static_assert(
298
      std::is_convertible_v<std::remove_cv_t<std::remove_reference_t<To>>*,
299
                            std::remove_cv_t<From>*>,
300
      "target type not derived from source type");
301
302
  absl::base_internal::ValidateDownCast<std::remove_reference_t<To>*>(
303
      std::addressof(f));
304
305
  return static_cast<To>(f);
306
}
307
308
ABSL_NAMESPACE_END
309
}  // namespace absl
310
311
#endif  // ABSL_BASE_CASTS_H_