From bf8b1d67d60d0eb01af0cfe87e2595d4fa525715 Mon Sep 17 00:00:00 2001 From: Adrien Ricciardi Date: Wed, 15 May 2024 11:28:34 +0200 Subject: [PATCH] sys: util: Add SIZEOF_FIELD() macro This macro allows to know the size of a struct member at compile time. Several parts of the Zephyr code are currently using directly the macro code. Also added a unit test. Signed-off-by: Adrien Ricciardi --- include/zephyr/sys/util.h | 10 ++++++++++ tests/unit/util/main.c | 15 +++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/include/zephyr/sys/util.h b/include/zephyr/sys/util.h index b457862bb97..fe04c058b1e 100644 --- a/include/zephyr/sys/util.h +++ b/include/zephyr/sys/util.h @@ -271,6 +271,16 @@ extern "C" { ((type *)(((char *)(ptr)) - offsetof(type, field))); \ }) +/** + * @brief Report the size of a struct field in bytes. + * + * @param type The structure containing the field of interest. + * @param member The field to return the size of. + * + * @return The field size. + */ +#define SIZEOF_FIELD(type, member) sizeof((((type *)0)->member)) + /** * @brief Concatenate input arguments * diff --git a/tests/unit/util/main.c b/tests/unit/util/main.c index 1e0bb67346a..f386ba0f789 100644 --- a/tests/unit/util/main.c +++ b/tests/unit/util/main.c @@ -803,4 +803,19 @@ ZTEST(util, test_CONCAT) zassert_equal(CONCAT(CAT_PART1, CONCAT(CAT_PART2, CAT_PART3)), 123); } +ZTEST(util, test_SIZEOF_FIELD) +{ + struct test_t { + uint32_t a; + uint8_t b; + uint8_t c[17]; + int16_t d; + }; + + BUILD_ASSERT(SIZEOF_FIELD(struct test_t, a) == 4, "The a member is 4-byte wide."); + BUILD_ASSERT(SIZEOF_FIELD(struct test_t, b) == 1, "The b member is 1-byte wide."); + BUILD_ASSERT(SIZEOF_FIELD(struct test_t, c) == 17, "The c member is 17-byte wide."); + BUILD_ASSERT(SIZEOF_FIELD(struct test_t, d) == 2, "The d member is 2-byte wide."); +} + ZTEST_SUITE(util, NULL, NULL, NULL, NULL, NULL);