From 01a49d3d194fb77eda33f4fc653522ce9b873288 Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Fri, 5 Nov 2021 15:27:51 +0100 Subject: [PATCH 1/2] core/include/kernel_defines.h: add index_of() macro --- core/include/kernel_defines.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/core/include/kernel_defines.h b/core/include/kernel_defines.h index df26784ea1..f52830e669 100644 --- a/core/include/kernel_defines.h +++ b/core/include/kernel_defines.h @@ -63,6 +63,16 @@ extern "C" { ((TYPE *) ((char *) (PTR) - offsetof(TYPE, MEMBER))) #endif +/** + * @def index_of(ARRAY, ELEMENT) + * @brief Returns the index of a pointer to an array element. + + * @param[in] ARRAY an array + * @param[in] ELEMENT pointer to an array element + * @return Index of the element in the array + */ +#define index_of(ARRAY, ELEMENT) (((uintptr_t)(ELEMENT) - (uintptr_t)(ARRAY)) / sizeof(*(ELEMENT))) + /** * @def NORETURN * @brief The *NORETURN* keyword tells the compiler to assume that the function From a803cab439465e48eb3debf891cd4b573a31f42e Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Fri, 5 Nov 2021 15:31:46 +0100 Subject: [PATCH 2/2] tests/unittests: add test for index_of() --- .../tests-kernel_defines/tests-kernel_defines.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/unittests/tests-kernel_defines/tests-kernel_defines.c b/tests/unittests/tests-kernel_defines/tests-kernel_defines.c index 9714a738df..fc8ac95c03 100644 --- a/tests/unittests/tests-kernel_defines/tests-kernel_defines.c +++ b/tests/unittests/tests-kernel_defines/tests-kernel_defines.c @@ -46,10 +46,20 @@ static void test_kernel_version(void) #endif } +static void test_index_of(void) +{ + unsigned foo[8]; + uint8_t bar[32]; + + TEST_ASSERT_EQUAL_INT(5, index_of(foo, &foo[5])); + TEST_ASSERT_EQUAL_INT(17, index_of(bar, &bar[17])); +} + Test *tests_kernel_defines_tests(void) { EMB_UNIT_TESTFIXTURES(fixtures) { new_TestFixture(test_kernel_version), + new_TestFixture(test_index_of), }; EMB_UNIT_TESTCALLER(kernel_defines_tests, NULL, NULL, fixtures);