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