blob: 70a7035c718972f2401eaf3090e9ebb57a119407 [file] [log] [blame]
Martin Stjernholmc15e7e42020-12-02 22:50:53 +00001/*
2 * Copyright (C) 2011 The Android Open Source Project
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 * http://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#ifndef ART_LIBARTBASE_BASE_CASTS_H_
18#define ART_LIBARTBASE_BASE_CASTS_H_
19
20#include <stdint.h>
21#include <string.h>
22
23#include <limits>
24#include <type_traits>
25
26#include <android-base/logging.h>
27
28#include "stl_util_identity.h"
29
30namespace art {
31
32// Use implicit_cast as a safe version of static_cast or const_cast
33// for upcasting in the type hierarchy (i.e. casting a pointer to Foo
34// to a pointer to SuperclassOfFoo or casting a pointer to Foo to
35// a const pointer to Foo).
36// When you use implicit_cast, the compiler checks that the cast is safe.
37// Such explicit implicit_casts are necessary in surprisingly many
38// situations where C++ demands an exact type match instead of an
39// argument type convertible to a target type.
40//
41// The From type can be inferred, so the preferred syntax for using
42// implicit_cast is the same as for static_cast etc.:
43//
44// implicit_cast<ToType>(expr)
45//
46// implicit_cast would have been part of the C++ standard library,
47// but the proposal was submitted too late. It will probably make
48// its way into the language in the future.
49template<typename To, typename From>
50inline To implicit_cast(From const &f) {
51 return f;
52}
53
54// When you upcast (that is, cast a pointer from type Foo to type
55// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts
56// always succeed. When you downcast (that is, cast a pointer from
57// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
58// how do you know the pointer is really of type SubclassOfFoo? It
59// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
Fairphone ODM25c12f52023-12-15 17:24:06 +080060// when you downcast, you should use this macro.
Martin Stjernholmc15e7e42020-12-02 22:50:53 +000061
62template<typename To, typename From> // use like this: down_cast<T*>(foo);
63inline To down_cast(From* f) { // so we only accept pointers
satayev499be972022-05-13 15:05:39 +000064 static_assert(std::is_base_of_v<From, std::remove_pointer_t<To>>,
Martin Stjernholmc15e7e42020-12-02 22:50:53 +000065 "down_cast unsafe as To is not a subtype of From");
66
67 return static_cast<To>(f);
68}
69
70template<typename To, typename From> // use like this: down_cast<T&>(foo);
71inline To down_cast(From& f) { // so we only accept references
satayev499be972022-05-13 15:05:39 +000072 static_assert(std::is_base_of_v<From, std::remove_reference_t<To>>,
Martin Stjernholmc15e7e42020-12-02 22:50:53 +000073 "down_cast unsafe as To is not a subtype of From");
74
75 return static_cast<To>(f);
76}
77
78template <class Dest, class Source>
79inline Dest bit_cast(const Source& source) {
80 // Compile time assertion: sizeof(Dest) == sizeof(Source)
81 // A compile error here means your Dest and Source have different sizes.
82 static_assert(sizeof(Dest) == sizeof(Source), "sizes should be equal");
83 Dest dest;
84 memcpy(&dest, &source, sizeof(dest));
85 return dest;
86}
87
88// A version of static_cast that DCHECKs that the value can be precisely represented
89// when converting to Dest.
90template <typename Dest, typename Source>
91constexpr Dest dchecked_integral_cast(Source source) {
92 DCHECK(
93 // Check that the value is within the lower limit of Dest.
94 (static_cast<intmax_t>(std::numeric_limits<Dest>::min()) <=
95 static_cast<intmax_t>(std::numeric_limits<Source>::min()) ||
96 source >= static_cast<Source>(std::numeric_limits<Dest>::min())) &&
97 // Check that the value is within the upper limit of Dest.
98 (static_cast<uintmax_t>(std::numeric_limits<Dest>::max()) >=
99 static_cast<uintmax_t>(std::numeric_limits<Source>::max()) ||
100 source <= static_cast<Source>(std::numeric_limits<Dest>::max())))
101 << "dchecked_integral_cast failed for " << source
102 << " (would be " << static_cast<Dest>(source) << ")";
103
104 return static_cast<Dest>(source);
105}
106
107// A version of dchecked_integral_cast casting between an integral type and an enum type.
108// When casting to an enum type, the cast does not check if the value corresponds to an enumerator.
109// When casting from an enum type, the target type can be omitted and the enum's underlying type
110// shall be used.
111
112template <typename Dest, typename Source>
113constexpr
satayev499be972022-05-13 15:05:39 +0000114std::enable_if_t<!std::is_enum_v<Source>, Dest> enum_cast(Source value) {
115 return static_cast<Dest>(dchecked_integral_cast<std::underlying_type_t<Dest>>(value));
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000116}
117
118template <typename Dest = void, typename Source>
119constexpr
satayev499be972022-05-13 15:05:39 +0000120typename std::enable_if_t<std::is_enum_v<Source>,
121 std::conditional_t<std::is_same_v<Dest, void>,
122 std::underlying_type<Source>,
123 Identity<Dest>>>::type
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000124enum_cast(Source value) {
satayev499be972022-05-13 15:05:39 +0000125 using return_type = typename std::conditional_t<std::is_same_v<Dest, void>,
126 std::underlying_type<Source>,
127 Identity<Dest>>::type;
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000128 return dchecked_integral_cast<return_type>(
satayev499be972022-05-13 15:05:39 +0000129 static_cast<std::underlying_type_t<Source>>(value));
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000130}
131
132// A version of reinterpret_cast<>() between pointers and int64_t/uint64_t
133// that goes through uintptr_t to avoid treating the pointer as "signed."
134
135template <typename Dest, typename Source>
136inline Dest reinterpret_cast64(Source source) {
137 // This is the overload for casting from int64_t/uint64_t to a pointer.
satayev499be972022-05-13 15:05:39 +0000138 static_assert(std::is_same_v<Source, int64_t> || std::is_same_v<Source, uint64_t>,
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000139 "Source must be int64_t or uint64_t.");
satayev499be972022-05-13 15:05:39 +0000140 static_assert(std::is_pointer_v<Dest>, "Dest must be a pointer.");
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000141 // Check that we don't lose any non-0 bits here.
142 DCHECK_EQ(static_cast<Source>(static_cast<uintptr_t>(source)), source);
143 return reinterpret_cast<Dest>(static_cast<uintptr_t>(source));
144}
145
146template <typename Dest, typename Source>
147inline Dest reinterpret_cast64(Source* ptr) {
148 // This is the overload for casting from a pointer to int64_t/uint64_t.
satayev499be972022-05-13 15:05:39 +0000149 static_assert(std::is_same_v<Dest, int64_t> || std::is_same_v<Dest, uint64_t>,
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000150 "Dest must be int64_t or uint64_t.");
151 static_assert(sizeof(uintptr_t) <= sizeof(Dest), "Expecting at most 64-bit pointers.");
152 return static_cast<Dest>(reinterpret_cast<uintptr_t>(ptr));
153}
154
155// A version of reinterpret_cast<>() between pointers and int32_t/uint32_t that enforces
156// zero-extension and checks that the values are converted without loss of precision.
157
158template <typename Dest, typename Source>
159inline Dest reinterpret_cast32(Source source) {
160 // This is the overload for casting from int32_t/uint32_t to a pointer.
satayev499be972022-05-13 15:05:39 +0000161 static_assert(std::is_same_v<Source, int32_t> || std::is_same_v<Source, uint32_t>,
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000162 "Source must be int32_t or uint32_t.");
satayev499be972022-05-13 15:05:39 +0000163 static_assert(std::is_pointer_v<Dest>, "Dest must be a pointer.");
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000164 // Check that we don't lose any non-0 bits here.
165 static_assert(sizeof(uintptr_t) >= sizeof(Source), "Expecting at least 32-bit pointers.");
166 return reinterpret_cast<Dest>(static_cast<uintptr_t>(static_cast<uint32_t>(source)));
167}
168
169template <typename Dest, typename Source>
170inline Dest reinterpret_cast32(Source* ptr) {
171 // This is the overload for casting from a pointer to int32_t/uint32_t.
satayev499be972022-05-13 15:05:39 +0000172 static_assert(std::is_same_v<Dest, int32_t> || std::is_same_v<Dest, uint32_t>,
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000173 "Dest must be int32_t or uint32_t.");
174 static_assert(sizeof(uintptr_t) >= sizeof(Dest), "Expecting at least 32-bit pointers.");
175 return static_cast<Dest>(dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(ptr)));
176}
177
178} // namespace art
179
180#endif // ART_LIBARTBASE_BASE_CASTS_H_