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);