Skip to content

Commit 1bef98a

Browse files
committed
sys: util_macro: Support macros as arguments
Adjusted GET_ARG_N and GET_ARGS_LESS_N to use UTIL_CAT instead of simple concatenation. This allows to use a macro as the argument N instead of only numbers. Adjusted the unit tests to showcase this. Signed-off-by: Greter Raffael <[email protected]>
1 parent bcc4689 commit 1bef98a

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

include/zephyr/sys/util_macro.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ extern "C" {
388388
*
389389
* @return Nth argument.
390390
*/
391-
#define GET_ARG_N(N, ...) Z_GET_ARG_##N(__VA_ARGS__)
391+
#define GET_ARG_N(N, ...) UTIL_CAT(Z_GET_ARG_, N)(__VA_ARGS__)
392392

393393
/**
394394
* @brief Strips n first arguments from the argument list.
@@ -398,7 +398,7 @@ extern "C" {
398398
*
399399
* @return argument list without N first arguments.
400400
*/
401-
#define GET_ARGS_LESS_N(N, ...) Z_GET_ARGS_LESS_##N(__VA_ARGS__)
401+
#define GET_ARGS_LESS_N(N, ...) UTIL_CAT(Z_GET_ARGS_LESS_, N)(__VA_ARGS__)
402402

403403
/**
404404
* @brief Like <tt>a || b</tt>, but does evaluation and

tests/unit/util/main.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -534,20 +534,25 @@ ZTEST(util, test_nested_FOR_EACH) {
534534
zassert_equal(a2, 2);
535535
}
536536

537+
#define TWO 2 /* to showcase that GET_ARG_N and GET_ARGS_LESS_N also work with macros */
538+
537539
ZTEST(util, test_GET_ARG_N) {
538540
int a = GET_ARG_N(1, 10, 100, 1000);
539541
int b = GET_ARG_N(2, 10, 100, 1000);
540542
int c = GET_ARG_N(3, 10, 100, 1000);
543+
int d = GET_ARG_N(TWO, 10, 100, 1000);
541544

542545
zassert_equal(a, 10);
543546
zassert_equal(b, 100);
544547
zassert_equal(c, 1000);
548+
zassert_equal(d, 100);
545549
}
546550

547551
ZTEST(util, test_GET_ARGS_LESS_N) {
548552
uint8_t a[] = { GET_ARGS_LESS_N(0, 1, 2, 3) };
549553
uint8_t b[] = { GET_ARGS_LESS_N(1, 1, 2, 3) };
550554
uint8_t c[] = { GET_ARGS_LESS_N(2, 1, 2, 3) };
555+
uint8_t d[] = { GET_ARGS_LESS_N(TWO, 1, 2, 3) };
551556

552557
zassert_equal(sizeof(a), 3);
553558

@@ -557,6 +562,9 @@ ZTEST(util, test_GET_ARGS_LESS_N) {
557562

558563
zassert_equal(sizeof(c), 1);
559564
zassert_equal(c[0], 3);
565+
566+
zassert_equal(sizeof(d), 1);
567+
zassert_equal(d[0], 3);
560568
}
561569

562570
ZTEST(util, test_mixing_GET_ARG_and_FOR_EACH) {

0 commit comments

Comments
 (0)