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 <aricciardi@baylibre.com>
This commit is contained in:
Adrien Ricciardi 2024-05-15 11:28:34 +02:00 committed by Alberto Escolar
commit bf8b1d67d6
2 changed files with 25 additions and 0 deletions

View file

@ -271,6 +271,16 @@ extern "C" {
((type *)(((char *)(ptr)) - offsetof(type, field))); \ ((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 * @brief Concatenate input arguments
* *

View file

@ -803,4 +803,19 @@ ZTEST(util, test_CONCAT)
zassert_equal(CONCAT(CAT_PART1, CONCAT(CAT_PART2, CAT_PART3)), 123); 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); ZTEST_SUITE(util, NULL, NULL, NULL, NULL, NULL);