3 * Copyright (c) 2020 Project CHIP Authors
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
20 #include <type_traits>
25 * A template function that casts a pointer of type From* to a pointer of type To*
26 * and verifies that both From and To are trivially copyable structures, size of
27 * To is not greater than size of From, and To doesn't have more strict alignment
28 * requirements than From. That is to make sure that access to fields of To is safe.
30 template <class ToPtr, class From>
31 std::enable_if_t<std::is_pointer<ToPtr>::value, ToPtr> SafePointerCast(From * from)
33 using To = std::remove_pointer_t<ToPtr>;
34 static_assert(std::is_trivially_copyable<From>(), "Casting from a non-trivially copyable type");
35 static_assert(std::is_trivially_copyable<To>(), "Casting to a non-trivially copyable type");
36 static_assert(sizeof(From) >= sizeof(To), "Casting to a bigger type");
37 static_assert(alignof(From) >= alignof(To), "Casting to a type with more strict alignment requirements");
38 return reinterpret_cast<ToPtr>(from);