LCOV - code coverage report
Current view: top level - lib/support - SafePointerCast.h (source / functions) Hit Total Coverage
Test: lcov_final.info Lines: 2 2 100.0 %
Date: 2024-02-15 08:20:41 Functions: 8 8 100.0 %

          Line data    Source code
       1             : /*
       2             :  *
       3             :  *    Copyright (c) 2020 Project CHIP Authors
       4             :  *
       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
       8             :  *
       9             :  *        http://www.apache.org/licenses/LICENSE-2.0
      10             :  *
      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.
      16             :  */
      17             : 
      18             : #pragma once
      19             : 
      20             : #include <type_traits>
      21             : 
      22             : namespace chip {
      23             : 
      24             : /**
      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.
      29             :  */
      30             : template <class ToPtr, class From>
      31       40170 : std::enable_if_t<std::is_pointer<ToPtr>::value, ToPtr> SafePointerCast(From * from)
      32             : {
      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       40170 :     return reinterpret_cast<ToPtr>(from);
      39             : }
      40             : 
      41             : } // namespace chip

Generated by: LCOV version 1.14