Skip to content

Commit

Permalink
sys: util: Add SIZEOF_FIELD() macro
Browse files Browse the repository at this point in the history
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.

(cherry picked from commit bf8b1d6)

Original-Signed-off-by: Adrien Ricciardi <aricciardi@baylibre.com>
GitOrigin-RevId: bf8b1d6
Change-Id: I0ef08f2e396379a05584e64e570c6187b7a24217
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/zephyr/+/5611392
Tested-by: Jeremy Bettis <jbettis@chromium.org>
Tested-by: Fabio Baltieri <fabiobaltieri@google.com>
Reviewed-by: Fabio Baltieri <fabiobaltieri@google.com>
Reviewed-by: Jeremy Bettis <jbettis@chromium.org>
Tested-by: ChromeOS Prod (Robot) <chromeos-ci-prod@chromeos-bot.iam.gserviceaccount.com>
Commit-Queue: Fabio Baltieri <fabiobaltieri@google.com>
  • Loading branch information
RICCIARDI-Adrien authored and Chromeos LUCI committed Jun 10, 2024
1 parent 22387f6 commit 850a0be
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
10 changes: 10 additions & 0 deletions include/zephyr/sys/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/util/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);

0 comments on commit 850a0be

Please sign in to comment.