Commit bf8b1d67 authored by Adrien Ricciardi's avatar Adrien Ricciardi Committed by Alberto Escolar
Browse files

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: default avatarAdrien Ricciardi <aricciardi@baylibre.com>
parent 34f4a0f6
Loading
Loading
Loading
Loading
+10 −0
Original line number Diff line number Diff line
@@ -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
 *
+15 −0
Original line number Diff line number Diff line
@@ -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);