xref: /aosp_15_r20/external/executorch/test/utils/alignment.h (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 #pragma once
10 
11 #include <cinttypes>
12 
13 #include <gmock/gmock.h> // For MATCHER_P
14 
15 namespace executorch {
16 namespace runtime {
17 namespace testing {
18 
19 /**
20  * Returns true if the address of `ptr` is a whole multiple of `alignment`.
21  */
is_aligned(const void * ptr,size_t alignment)22 inline bool is_aligned(const void* ptr, size_t alignment) {
23   auto addr = reinterpret_cast<uintptr_t>(ptr);
24   return addr % alignment == 0;
25 }
26 
27 /**
28  * Lets gtest users write `EXPECT_THAT(ptr, IsAlignedTo(alignment))` or
29  * `EXPECT_THAT(ptr, Not(IsAlignedTo(alignment)))`.
30  *
31  * See also `EXPECT_ALIGNED()`.
32  */
33 MATCHER_P(IsAlignedTo, other, "") {
34   return is_aligned(arg, other);
35 }
36 
37 /*
38  * Helpers for checking the alignment of a pointer.
39  */
40 
41 #define EXPECT_ALIGNED(ptr, alignment) \
42   EXPECT_THAT((ptr), executorch::runtime::testing::IsAlignedTo((alignment)))
43 #define ASSERT_ALIGNED(ptr, alignment) \
44   ASSERT_THAT((ptr), executorch::runtime::testing::IsAlignedTo((alignment)))
45 
46 } // namespace testing
47 } // namespace runtime
48 } // namespace executorch
49