Coverage Report

Created: 2026-09-14 06:45

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