Skip to content

Commit ae2cb14

Browse files
ycsinfabiobaltieri
authored andcommitted
include: sys: util: implement NUM_VA_ARGS
This macro count the number of arguments in the variable arguments list. Added test for it in `tests/lib/sys_util`. Signed-off-by: Yong Cong Sin <[email protected]>
1 parent e44d2e6 commit ae2cb14

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

include/zephyr/sys/util_macro.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,17 @@ extern "C" {
635635
20, 19, 18, 17, 16, 15, 14, 13, 12, 11, \
636636
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ~)
637637

638+
/**
639+
* @brief Number of arguments in the variable arguments list.
640+
*
641+
* @note Supports up to 63 arguments.
642+
*
643+
* @param ... List of arguments
644+
* @return Number of variadic arguments in the argument list
645+
*/
646+
#define NUM_VA_ARGS(...) \
647+
COND_CODE_1(IS_EMPTY(__VA_ARGS__), (0), (UTIL_INC(NUM_VA_ARGS_LESS_1(__VA_ARGS__))))
648+
638649
/**
639650
* @brief Mapping macro that pastes results together
640651
*

tests/lib/sys_util/src/main.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,21 @@ ZTEST(sys_util, test_wait_for)
3737
end = k_cycle_get_32();
3838
zassert_true(end-start >= expected, "wait for 1ms");
3939
}
40+
41+
/**
42+
* @brief Test NUM_VA_ARGS works as expected with typical use cases
43+
*
44+
* @see NUM_VA_ARGS()
45+
*/
46+
47+
ZTEST(sys_util, test_NUM_VA_ARGS)
48+
{
49+
zassert_equal(0, NUM_VA_ARGS());
50+
zassert_equal(1, NUM_VA_ARGS(_1));
51+
zassert_equal(2, NUM_VA_ARGS(_1, _2));
52+
/* support up to 63 args */
53+
zassert_equal(63, NUM_VA_ARGS(LISTIFY(63, ~, (,))));
54+
}
4055
/**
4156
* @}
4257
*/

0 commit comments

Comments
 (0)