Zephyr API Documentation  3.6.99
A Scalable Open Source RTOS
Loading...
Searching...
No Matches
Utility Functions

Macros

#define POINTER_TO_UINT(x)   ((uintptr_t) (x))
 Cast x, a pointer, to an unsigned integer.
 
#define UINT_TO_POINTER(x)   ((void *) (uintptr_t) (x))
 Cast x, an unsigned integer, to a void*.
 
#define POINTER_TO_INT(x)   ((intptr_t) (x))
 Cast x, a pointer, to a signed integer.
 
#define INT_TO_POINTER(x)   ((void *) (intptr_t) (x))
 Cast x, a signed integer, to a void*.
 
#define BITS_PER_LONG   (__CHAR_BIT__ * __SIZEOF_LONG__)
 Number of bits in a long int.
 
#define BITS_PER_LONG_LONG   (__CHAR_BIT__ * __SIZEOF_LONG_LONG__)
 Number of bits in a long long int.
 
#define GENMASK(h, l)    (((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
 Create a contiguous bitmask starting at bit position l and ending at position h.
 
#define GENMASK64(h, l)    (((~0ULL) - (1ULL << (l)) + 1) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))
 Create a contiguous 64-bit bitmask starting at bit position l and ending at position h.
 
#define LSB_GET(value)   ((value) & -(value))
 Extract the Least Significant Bit from value.
 
#define FIELD_GET(mask, value)   (((value) & (mask)) / LSB_GET(mask))
 Extract a bitfield element from value corresponding to the field mask mask.
 
#define FIELD_PREP(mask, value)   (((value) * LSB_GET(mask)) & (mask))
 Prepare a bitfield element using value with mask representing its field position and width.
 
#define ZERO_OR_COMPILE_ERROR(cond)   ((int) sizeof(char[1 - 2 * !(cond)]) - 1)
 0 if cond is true-ish; causes a compile error otherwise.
 
#define IS_ARRAY(array)
 Zero if array has an array type, a compile error otherwise.
 
#define ARRAY_SIZE(array)    ((size_t) (IS_ARRAY(array) + (sizeof(array) / sizeof((array)[0]))))
 Number of elements in the given array.
 
#define IS_ARRAY_ELEMENT(array, ptr)
 Whether ptr is an element of array.
 
#define ARRAY_INDEX(array, ptr)
 Index of ptr within array.
 
#define PART_OF_ARRAY(array, ptr)
 Check if a pointer ptr lies within array.
 
#define ARRAY_INDEX_FLOOR(array, ptr)
 Array-index of ptr within array, rounded down.
 
#define ARRAY_FOR_EACH(array, idx)   for (size_t idx = 0; (idx) < ARRAY_SIZE(array); ++(idx))
 Iterate over members of an array using an index variable.
 
#define ARRAY_FOR_EACH_PTR(array, ptr)
 Iterate over members of an array using a pointer.
 
#define SAME_TYPE(a, b)   __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
 Validate if two entities have a compatible type.
 
#define CONTAINER_OF_VALIDATE(ptr, type, field)
 Validate CONTAINER_OF parameters, only applies to C mode.
 
#define CONTAINER_OF(ptr, type, field)
 Get a pointer to a structure containing the element.
 
#define SIZEOF_FIELD(type, member)   sizeof((((type *)0)->member))
 Report the size of a struct field in bytes.
 
#define CONCAT(...)    UTIL_CAT(_CONCAT_, NUM_VA_ARGS_LESS_1(__VA_ARGS__))(__VA_ARGS__)
 Concatenate input arguments.
 
#define IS_ALIGNED(ptr, align)   (((uintptr_t)(ptr)) % (align) == 0)
 Check if ptr is aligned to align alignment.
 
#define ROUND_UP(x, align)
 Value of x rounded up to the next multiple of align.
 
#define ROUND_DOWN(x, align)    (((unsigned long)(x) / (unsigned long)(align)) * (unsigned long)(align))
 Value of x rounded down to the previous multiple of align.
 
#define WB_UP(x)   ROUND_UP(x, sizeof(void *))
 Value of x rounded up to the next word boundary.
 
#define WB_DN(x)   ROUND_DOWN(x, sizeof(void *))
 Value of x rounded down to the previous word boundary.
 
#define DIV_ROUND_UP(n, d)   (((n) + (d) - 1) / (d))
 Divide and round up.
 
#define DIV_ROUND_CLOSEST(n, d)
 Divide and round to the nearest integer.
 
#define ceiling_fraction(numerator, divider)
 Ceiling function applied to numerator / divider as a fraction.
 
#define MAX(a, b)   (((a) > (b)) ? (a) : (b))
 Obtain the maximum of two values.
 
#define MIN(a, b)   (((a) < (b)) ? (a) : (b))
 Obtain the minimum of two values.
 
#define CLAMP(val, low, high)   (((val) <= (low)) ? (low) : MIN(val, high))
 Clamp a value to a given range.
 
#define IN_RANGE(val, min, max)   ((val) >= (min) && (val) <= (max))
 Checks if a value is within range.
 
#define LOG2(x)   ((x) < 1 ? -1 : __z_log2(x))
 Compute log2(x)
 
#define LOG2CEIL(x)   ((x) < 1 ? 0 : __z_log2((x)-1) + 1)
 Compute ceil(log2(x))
 
#define NHPOT(x)   ((x) < 1 ? 1 : ((x) > (1ULL<<63) ? 0 : 1ULL << LOG2CEIL(x)))
 Compute next highest power of two.
 
#define KB(x)   ((x) << 10)
 Number of bytes in x kibibytes.
 
#define MB(x)   (KB(x) << 10)
 Number of bytes in x mebibytes.
 
#define GB(x)   (MB(x) << 10)
 Number of bytes in x gibibytes.
 
#define KHZ(x)   ((x) * 1000)
 Number of Hz in x kHz.
 
#define MHZ(x)   (KHZ(x) * 1000)
 Number of Hz in x MHz.
 
#define WAIT_FOR(expr, timeout, delay_stmt)
 Wait for an expression to return true with a timeout.
 
#define BIT(n)   (1UL << (n))
 Unsigned integer with bit position n set (signed in assembly language).
 
#define BIT64(_n)   (1ULL << (_n))
 64-bit unsigned integer with bit position _n set.
 
#define WRITE_BIT(var, bit, set)    ((var) = (set) ? ((var) | BIT(bit)) : ((var) & ~BIT(bit)))
 Set or clear a bit depending on a boolean value.
 
#define BIT_MASK(n)   (BIT(n) - 1UL)
 Bit mask with bits 0 through n-1 (inclusive) set, or 0 if n is 0.
 
#define BIT64_MASK(n)   (BIT64(n) - 1ULL)
 64-bit bit mask with bits 0 through n-1 (inclusive) set, or 0 if n is 0.
 
#define IS_POWER_OF_TWO(x)   (((x) != 0U) && (((x) & ((x) - 1U)) == 0U))
 Check if a x is a power of two.
 
#define IS_SHIFTED_BIT_MASK(m, s)   (!(((m) >> (s)) & (((m) >> (s)) + 1U)))
 Check if bits are set continuously from the specified bit.
 
#define IS_BIT_MASK(m)   IS_SHIFTED_BIT_MASK(m, 0)
 Check if bits are set continuously from the LSB.
 
#define IS_ENABLED(config_macro)   Z_IS_ENABLED1(config_macro)
 Check for macro definition in compiler-visible expressions.
 
#define COND_CODE_1(_flag, _if_1_code, _else_code)    Z_COND_CODE_1(_flag, _if_1_code, _else_code)
 Insert code depending on whether _flag expands to 1 or not.
 
#define COND_CODE_0(_flag, _if_0_code, _else_code)    Z_COND_CODE_0(_flag, _if_0_code, _else_code)
 Like COND_CODE_1() except tests if _flag is 0.
 
#define IF_ENABLED(_flag, _code)    COND_CODE_1(_flag, _code, ())
 Insert code if _flag is defined and equals 1.
 
#define IF_DISABLED(_flag, _code)    COND_CODE_1(_flag, (), _code)
 Insert code if _flag is not defined as 1.
 
#define IS_EMPTY(...)   Z_IS_EMPTY_(__VA_ARGS__)
 Check if a macro has a replacement expression.
 
#define IS_EQ(a, b)   Z_IS_EQ(a, b)
 Like a == b, but does evaluation and short-circuiting at C preprocessor time.
 
#define LIST_DROP_EMPTY(...)    Z_LIST_DROP_FIRST(FOR_EACH(Z_LIST_NO_EMPTIES, (), __VA_ARGS__))
 Remove empty arguments from list.
 
#define EMPTY
 Macro with an empty expansion.
 
#define IDENTITY(V)   V
 Macro that expands to its argument.
 
#define GET_ARG_N(N, ...)   Z_GET_ARG_##N(__VA_ARGS__)
 Get nth argument from argument list.
 
#define GET_ARGS_LESS_N(N, ...)   Z_GET_ARGS_LESS_##N(__VA_ARGS__)
 Strips n first arguments from the argument list.
 
#define UTIL_OR(a, b)   COND_CODE_1(UTIL_BOOL(a), (a), (b))
 Like a || b, but does evaluation and short-circuiting at C preprocessor time.
 
#define UTIL_AND(a, b)   COND_CODE_1(UTIL_BOOL(a), (b), (0))
 Like a && b, but does evaluation and short-circuiting at C preprocessor time.
 
#define UTIL_INC(x)   UTIL_PRIMITIVE_CAT(Z_UTIL_INC_, x)
 UTIL_INC(x) for an integer literal x from 0 to 4095 expands to an integer literal whose value is x+1.
 
#define UTIL_DEC(x)   UTIL_PRIMITIVE_CAT(Z_UTIL_DEC_, x)
 UTIL_DEC(x) for an integer literal x from 0 to 4095 expands to an integer literal whose value is x-1.
 
#define UTIL_X2(y)   UTIL_PRIMITIVE_CAT(Z_UTIL_X2_, y)
 UTIL_X2(y) for an integer literal y from 0 to 4095 expands to an integer literal whose value is 2y.
 
#define LISTIFY(LEN, F, sep, ...)   UTIL_CAT(Z_UTIL_LISTIFY_, LEN)(F, sep, __VA_ARGS__)
 Generates a sequence of code with configurable separator.
 
#define FOR_EACH(F, sep, ...)    Z_FOR_EACH(F, sep, REVERSE_ARGS(__VA_ARGS__))
 Call a macro F on each provided argument with a given separator between each call.
 
#define FOR_EACH_NONEMPTY_TERM(F, term, ...)
 Like FOR_EACH(), but with a terminator instead of a separator, and drops empty elements from the argument list.
 
#define FOR_EACH_IDX(F, sep, ...)    Z_FOR_EACH_IDX(F, sep, REVERSE_ARGS(__VA_ARGS__))
 Call macro F on each provided argument, with the argument's index as an additional parameter.
 
#define FOR_EACH_FIXED_ARG(F, sep, fixed_arg, ...)    Z_FOR_EACH_FIXED_ARG(F, sep, fixed_arg, REVERSE_ARGS(__VA_ARGS__))
 Call macro F on each provided argument, with an additional fixed argument as a parameter.
 
#define FOR_EACH_IDX_FIXED_ARG(F, sep, fixed_arg, ...)    Z_FOR_EACH_IDX_FIXED_ARG(F, sep, fixed_arg, REVERSE_ARGS(__VA_ARGS__))
 Calls macro F for each variable argument with an index and fixed argument.
 
#define REVERSE_ARGS(...)    Z_FOR_EACH_ENGINE(Z_FOR_EACH_EXEC, (,), Z_BYPASS, _, __VA_ARGS__)
 Reverse arguments order.
 
#define NUM_VA_ARGS_LESS_1(...)
 Number of arguments in the variable arguments list minus one.
 
#define NUM_VA_ARGS(...)    COND_CODE_1(IS_EMPTY(__VA_ARGS__), (0), (UTIL_INC(NUM_VA_ARGS_LESS_1(__VA_ARGS__))))
 Number of arguments in the variable arguments list.
 
#define MACRO_MAP_CAT(...)   MACRO_MAP_CAT_(__VA_ARGS__)
 Mapping macro that pastes results together.
 
#define MACRO_MAP_CAT_N(N, ...)   MACRO_MAP_CAT_N_(N, __VA_ARGS__)
 Mapping macro that pastes a fixed number of results together.
 

Functions

static bool is_power_of_two (unsigned int x)
 Is x a power of two?
 
static ALWAYS_INLINE bool is_null_no_warn (void *p)
 Is p equal to NULL?
 
static int64_t arithmetic_shift_right (int64_t value, uint8_t shift)
 Arithmetic shift right.
 
static void bytecpy (void *dst, const void *src, size_t size)
 byte by byte memcpy.
 
static void byteswp (void *a, void *b, size_t size)
 byte by byte swap.
 
int char2hex (char c, uint8_t *x)
 Convert a single character into a hexadecimal nibble.
 
int hex2char (uint8_t x, char *c)
 Convert a single hexadecimal nibble into a character.
 
size_t bin2hex (const uint8_t *buf, size_t buflen, char *hex, size_t hexlen)
 Convert a binary array into string representation.
 
size_t hex2bin (const char *hex, size_t hexlen, uint8_t *buf, size_t buflen)
 Convert a hexadecimal string into a binary array.
 
static uint8_t bcd2bin (uint8_t bcd)
 Convert a binary coded decimal (BCD 8421) value to binary.
 
static uint8_t bin2bcd (uint8_t bin)
 Convert a binary value to binary coded decimal (BCD 8421).
 
uint8_t u8_to_dec (char *buf, uint8_t buflen, uint8_t value)
 Convert a uint8_t into a decimal string representation.
 
static int32_t sign_extend (uint32_t value, uint8_t index)
 Sign extend an 8, 16 or 32 bit value using the index bit as sign bit.
 
static int64_t sign_extend_64 (uint64_t value, uint8_t index)
 Sign extend a 64 bit value using the index bit as sign bit.
 
char * utf8_trunc (char *utf8_str)
 Properly truncate a NULL-terminated UTF-8 string.
 
char * utf8_lcpy (char *dst, const char *src, size_t n)
 Copies a UTF-8 encoded string from src to dst.
 
static void mem_xor_n (uint8_t *dst, const uint8_t *src1, const uint8_t *src2, size_t len)
 XOR n bytes.
 
static void mem_xor_32 (uint8_t dst[4], const uint8_t src1[4], const uint8_t src2[4])
 XOR 32 bits.
 
static void mem_xor_128 (uint8_t dst[16], const uint8_t src1[16], const uint8_t src2[16])
 XOR 128 bits.
 

Detailed Description

Since
2.4
Version
0.1.0

Macro Definition Documentation

◆ ARRAY_FOR_EACH

#define ARRAY_FOR_EACH (   array,
  idx 
)    for (size_t idx = 0; (idx) < ARRAY_SIZE(array); ++(idx))

#include <zephyr/sys/util.h>

Iterate over members of an array using an index variable.

Parameters
arraythe array in question
idxname of array index variable

◆ ARRAY_FOR_EACH_PTR

#define ARRAY_FOR_EACH_PTR (   array,
  ptr 
)

#include <zephyr/sys/util.h>

Value:
for (__typeof__(*(array)) *ptr = (array); (size_t)((ptr) - (array)) < ARRAY_SIZE(array); \
++(ptr))
#define ARRAY_SIZE(array)
Number of elements in the given array.
Definition: util.h:127
Size of off_t must be equal or less than size of size_t
Definition: retained_mem.h:28

Iterate over members of an array using a pointer.

Parameters
arraythe array in question
ptrpointer to an element of array

◆ ARRAY_INDEX

#define ARRAY_INDEX (   array,
  ptr 
)

#include <zephyr/sys/util.h>

Value:
({ \
__ASSERT_NO_MSG(IS_ARRAY_ELEMENT(array, ptr)); \
(__typeof__((array)[0]) *)(ptr) - (array); \
})
#define IS_ARRAY_ELEMENT(array, ptr)
Whether ptr is an element of array.
Definition: util.h:146

Index of ptr within array.

With CONFIG_ASSERT=y, this macro will trigger a runtime assertion when ptr does not fall into the range of array or when ptr is not aligned to an array-element boundary of array.

In C, passing a pointer as array causes a compile error.

Parameters
arraythe array in question
ptrpointer to an element of array
Returns
the array index of ptr within array, on success

◆ ARRAY_INDEX_FLOOR

#define ARRAY_INDEX_FLOOR (   array,
  ptr 
)

#include <zephyr/sys/util.h>

Value:
({ \
__ASSERT_NO_MSG(PART_OF_ARRAY(array, ptr)); \
(POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) / sizeof((array)[0]); \
})
#define PART_OF_ARRAY(array, ptr)
Check if a pointer ptr lies within array.
Definition: util.h:181
#define POINTER_TO_UINT(x)
Cast x, a pointer, to an unsigned integer.
Definition: util.h:48

Array-index of ptr within array, rounded down.

This macro behaves much like ARRAY_INDEX with the notable difference that it accepts any ptr in the range of array rather than exclusively a ptr aligned to an array-element boundary of array.

With CONFIG_ASSERT=y, this macro will trigger a runtime assertion when ptr does not fall into the range of array.

In C, passing a pointer as array causes a compile error.

Parameters
arraythe array in question
ptrpointer to an element of array
Returns
the array index of ptr within array, on success

◆ ARRAY_SIZE

#define ARRAY_SIZE (   array)     ((size_t) (IS_ARRAY(array) + (sizeof(array) / sizeof((array)[0]))))

#include <zephyr/sys/util.h>

Number of elements in the given array.

In C++, due to language limitations, this will accept as array any type that implements operator[]. The results may not be particularly meaningful in this case.

In C, passing a pointer as array causes a compile error.

◆ BIT

#define BIT (   n)    (1UL << (n))

#include <zephyr/sys/util_macro.h>

Unsigned integer with bit position n set (signed in assembly language).

◆ BIT64

#define BIT64 (   _n)    (1ULL << (_n))

#include <zephyr/sys/util_macro.h>

64-bit unsigned integer with bit position _n set.

◆ BIT64_MASK

#define BIT64_MASK (   n)    (BIT64(n) - 1ULL)

#include <zephyr/sys/util_macro.h>

64-bit bit mask with bits 0 through n-1 (inclusive) set, or 0 if n is 0.

◆ BIT_MASK

#define BIT_MASK (   n)    (BIT(n) - 1UL)

#include <zephyr/sys/util_macro.h>

Bit mask with bits 0 through n-1 (inclusive) set, or 0 if n is 0.

◆ BITS_PER_LONG

#define BITS_PER_LONG   (__CHAR_BIT__ * __SIZEOF_LONG__)

#include <zephyr/sys/util.h>

Number of bits in a long int.

◆ BITS_PER_LONG_LONG

#define BITS_PER_LONG_LONG   (__CHAR_BIT__ * __SIZEOF_LONG_LONG__)

#include <zephyr/sys/util.h>

Number of bits in a long long int.

◆ ceiling_fraction

#define ceiling_fraction (   numerator,
  divider 
)

#include <zephyr/sys/util.h>

Value:
__DEPRECATED_MACRO \
DIV_ROUND_UP(numerator, divider)

Ceiling function applied to numerator / divider as a fraction.

Deprecated:
Use DIV_ROUND_UP() instead.

◆ CLAMP

#define CLAMP (   val,
  low,
  high 
)    (((val) <= (low)) ? (low) : MIN(val, high))

#include <zephyr/sys/util.h>

Clamp a value to a given range.

Note
Arguments are evaluated multiple times. Use Z_CLAMP for a GCC-only, single evaluation version.
Parameters
valValue to be clamped.
lowLowest allowed value (inclusive).
highHighest allowed value (inclusive).
Returns
Clamped value.

◆ CONCAT

#define CONCAT (   ...)     UTIL_CAT(_CONCAT_, NUM_VA_ARGS_LESS_1(__VA_ARGS__))(__VA_ARGS__)

#include <zephyr/sys/util.h>

Concatenate input arguments.

Concatenate provided tokens into a combined token during the preprocessor pass. This can be used to, for ex., build an identifier out of multiple parts, where one of those parts may be, for ex, a number, another macro, or a macro argument.

Parameters
...Tokens to concatencate
Returns
Concatenated token.

◆ COND_CODE_0

#define COND_CODE_0 (   _flag,
  _if_0_code,
  _else_code 
)     Z_COND_CODE_0(_flag, _if_0_code, _else_code)

#include <zephyr/sys/util_macro.h>

Like COND_CODE_1() except tests if _flag is 0.

This is like COND_CODE_1(), except that it tests whether _flag expands to the integer literal 0. It expands to _if_0_code if so, and _else_code otherwise; both of these must be enclosed in parentheses.

Parameters
_flagevaluated flag
_if_0_coderesult if _flag expands to 0; must be in parentheses
_else_coderesult otherwise; must be in parentheses
See also
COND_CODE_1()

◆ COND_CODE_1

#define COND_CODE_1 (   _flag,
  _if_1_code,
  _else_code 
)     Z_COND_CODE_1(_flag, _if_1_code, _else_code)

#include <zephyr/sys/util_macro.h>

Insert code depending on whether _flag expands to 1 or not.

This relies on similar tricks as IS_ENABLED(), but as the result of _flag expansion, results in either _if_1_code or _else_code is expanded.

To prevent the preprocessor from treating commas as argument separators, the _if_1_code and _else_code expressions must be inside brackets/parentheses: (). These are stripped away during macro expansion.

Example:

COND_CODE_1(CONFIG_FLAG, (uint32_t x;), (there_is_no_flag();))

If CONFIG_FLAG is defined to 1, this expands to:

uint32_t x;

It expands to there_is_no_flag(); otherwise.

This could be used as an alternative to:

#if defined(CONFIG_FLAG) && (CONFIG_FLAG == 1)
#define MAYBE_DECLARE(x) uint32_t x
#else
#define MAYBE_DECLARE(x) there_is_no_flag()
#endif

MAYBE_DECLARE(x);

However, the advantage of COND_CODE_1() is that code is resolved in place where it is used, while the #if method defines MAYBE_DECLARE on two lines and requires it to be invoked again on a separate line. This makes COND_CODE_1() more concise and also sometimes more useful when used within another macro's expansion.

Note
_flag can be the result of preprocessor expansion, e.g. an expression involving NUM_VA_ARGS_LESS_1(...). However, _if_1_code is only expanded if _flag expands to the integer literal 1. Integer expressions that evaluate to 1, e.g. after doing some arithmetic, will not work.
Parameters
_flagevaluated flag
_if_1_coderesult if _flag expands to 1; must be in parentheses
_else_coderesult otherwise; must be in parentheses

◆ CONTAINER_OF

#define CONTAINER_OF (   ptr,
  type,
  field 
)

#include <zephyr/sys/util.h>

Value:
({ \
CONTAINER_OF_VALIDATE(ptr, type, field) \
((type *)(((char *)(ptr)) - offsetof(type, field))); \
})

Get a pointer to a structure containing the element.

Example:

 struct foo {
    int bar;
 };

 struct foo my_foo;
 int *ptr = &my_foo.bar;

 struct foo *container = CONTAINER_OF(ptr, struct foo, bar);

Above, container points at my_foo.

Parameters
ptrpointer to a structure element
typename of the type that ptr is an element of
fieldthe name of the field within the struct ptr points to
Returns
a pointer to the structure that contains ptr

◆ CONTAINER_OF_VALIDATE

#define CONTAINER_OF_VALIDATE (   ptr,
  type,
  field 
)

#include <zephyr/sys/util.h>

Value:
BUILD_ASSERT(SAME_TYPE(*(ptr), ((type *)0)->field) || \
SAME_TYPE(*(ptr), void), \
"pointer type mismatch in CONTAINER_OF");
#define SAME_TYPE(a, b)
Validate if two entities have a compatible type.
Definition: util.h:233

Validate CONTAINER_OF parameters, only applies to C mode.

◆ DIV_ROUND_CLOSEST

#define DIV_ROUND_CLOSEST (   n,
  d 
)

#include <zephyr/sys/util.h>

Value:
((((n) < 0) ^ ((d) < 0)) ? ((n) - ((d) / 2)) / (d) : \
((n) + ((d) / 2)) / (d))
irp nz macro MOVR cc d
Definition: asm-macro-32-bit-gnu.h:11

Divide and round to the nearest integer.

Example:

DIV_ROUND_CLOSEST(5, 2); // 3
DIV_ROUND_CLOSEST(5, -2); // -3
DIV_ROUND_CLOSEST(5, 3); // 2
#define DIV_ROUND_CLOSEST(n, d)
Divide and round to the nearest integer.
Definition: util.h:353
Parameters
nNumerator.
dDenominator.
Returns
The result of n / d, rounded to the nearest integer.

◆ DIV_ROUND_UP

#define DIV_ROUND_UP (   n,
  d 
)    (((n) + (d) - 1) / (d))

#include <zephyr/sys/util.h>

Divide and round up.

Example:

DIV_ROUND_UP(1, 2); // 1
DIV_ROUND_UP(3, 2); // 2
#define DIV_ROUND_UP(n, d)
Divide and round up.
Definition: util.h:336
Parameters
nNumerator.
dDenominator.
Returns
The result of n / d, rounded up.

◆ EMPTY

#define EMPTY

#include <zephyr/sys/util_macro.h>

Macro with an empty expansion.

This trivial definition is provided for readability when a macro should expand to an empty result, which e.g. is sometimes needed to silence checkpatch.

Example:

 #define LIST_ITEM(n) , item##n

The above would cause checkpatch to complain, but:

 #define LIST_ITEM(n) EMPTY, item##n

would not.

◆ FIELD_GET

#define FIELD_GET (   mask,
  value 
)    (((value) & (mask)) / LSB_GET(mask))

#include <zephyr/sys/util.h>

Extract a bitfield element from value corresponding to the field mask mask.

◆ FIELD_PREP

#define FIELD_PREP (   mask,
  value 
)    (((value) * LSB_GET(mask)) & (mask))

#include <zephyr/sys/util.h>

Prepare a bitfield element using value with mask representing its field position and width.

The result should be combined with other fields using a logical OR.

◆ FOR_EACH

#define FOR_EACH (   F,
  sep,
  ... 
)     Z_FOR_EACH(F, sep, REVERSE_ARGS(__VA_ARGS__))

#include <zephyr/sys/util_macro.h>

Call a macro F on each provided argument with a given separator between each call.

Example:

#define F(x) int a##x
FOR_EACH(F, (;), 4, 5, 6);

This expands to:

int a4;
int a5;
int a6;
Parameters
FMacro to invoke
sepSeparator (e.g. comma or semicolon). Must be in parentheses; this is required to enable providing a comma as separator.
...Variable argument list. The macro F is invoked as F(element) for each element in the list.

◆ FOR_EACH_FIXED_ARG

#define FOR_EACH_FIXED_ARG (   F,
  sep,
  fixed_arg,
  ... 
)     Z_FOR_EACH_FIXED_ARG(F, sep, fixed_arg, REVERSE_ARGS(__VA_ARGS__))

#include <zephyr/sys/util_macro.h>

Call macro F on each provided argument, with an additional fixed argument as a parameter.

This is like FOR_EACH(), except F should be a macro which takes two arguments: F(variable_arg, fixed_arg).

Example:

static void func(int val, void *dev);
FOR_EACH_FIXED_ARG(func, (;), dev, 4, 5, 6);

This expands to:

func(4, dev);
func(5, dev);
func(6, dev);
Parameters
FMacro to invoke
sepSeparator (e.g. comma or semicolon). Must be in parentheses; this is required to enable providing a comma as separator.
fixed_argFixed argument passed to F as the second macro parameter.
...Variable argument list. The macro F is invoked as F(element, fixed_arg) for each element in the list.

◆ FOR_EACH_IDX

#define FOR_EACH_IDX (   F,
  sep,
  ... 
)     Z_FOR_EACH_IDX(F, sep, REVERSE_ARGS(__VA_ARGS__))

#include <zephyr/sys/util_macro.h>

Call macro F on each provided argument, with the argument's index as an additional parameter.

This is like FOR_EACH(), except F should be a macro which takes two arguments: F(index, variable_arg).

Example:

#define F(idx, x) int a##idx = x
FOR_EACH_IDX(F, (;), 4, 5, 6);

This expands to:

int a0 = 4;
int a1 = 5;
int a2 = 6;
Parameters
FMacro to invoke
sepSeparator (e.g. comma or semicolon). Must be in parentheses; this is required to enable providing a comma as separator.
...Variable argument list. The macro F is invoked as F(index, element) for each element in the list.

◆ FOR_EACH_IDX_FIXED_ARG

#define FOR_EACH_IDX_FIXED_ARG (   F,
  sep,
  fixed_arg,
  ... 
)     Z_FOR_EACH_IDX_FIXED_ARG(F, sep, fixed_arg, REVERSE_ARGS(__VA_ARGS__))

#include <zephyr/sys/util_macro.h>

Calls macro F for each variable argument with an index and fixed argument.

This is like the combination of FOR_EACH_IDX() with FOR_EACH_FIXED_ARG().

Example:

#define F(idx, x, fixed_arg) int fixed_arg##idx = x
FOR_EACH_IDX_FIXED_ARG(F, (;), a, 4, 5, 6);

This expands to:

int a0 = 4;
int a1 = 5;
int a2 = 6;
Parameters
FMacro to invoke
sepSeparator (e.g. comma or semicolon). Must be in parentheses; This is required to enable providing a comma as separator.
fixed_argFixed argument passed to F as the third macro parameter.
...Variable list of arguments. The macro F is invoked as F(index, element, fixed_arg) for each element in the list.

◆ FOR_EACH_NONEMPTY_TERM

#define FOR_EACH_NONEMPTY_TERM (   F,
  term,
  ... 
)

#include <zephyr/sys/util_macro.h>

Value:
/* are there zero non-empty arguments ? */ \
NUM_VA_ARGS_LESS_1(LIST_DROP_EMPTY(__VA_ARGS__, _)), \
/* if so, expand to nothing */ \
(), \
/* otherwise, expand to: */ \
(/* FOR_EACH() on nonempty elements, */ \
FOR_EACH(F, term, LIST_DROP_EMPTY(__VA_ARGS__)) \
/* plus a final terminator */ \
__DEBRACKET term \
))
#define FOR_EACH(F, sep,...)
Call a macro F on each provided argument with a given separator between each call.
Definition: util_macro.h:465
#define COND_CODE_0(_flag, _if_0_code, _else_code)
Like COND_CODE_1() except tests if _flag is 0.
Definition: util_macro.h:195
#define NUM_VA_ARGS_LESS_1(...)
Number of arguments in the variable arguments list minus one.
Definition: util_macro.h:631
#define LIST_DROP_EMPTY(...)
Remove empty arguments from list.
Definition: util_macro.h:315

Like FOR_EACH(), but with a terminator instead of a separator, and drops empty elements from the argument list.

The sep argument to FOR_EACH(F, (sep), a, b) is a separator which is placed between calls to F, like this:

FOR_EACH(F, (sep), a, b) // F(a) sep F(b)
                         //               ^^^ no sep here!

By contrast, the term argument to FOR_EACH_NONEMPTY_TERM(F, (term), a, b) is added after each time F appears in the expansion:

FOR_EACH_NONEMPTY_TERM(F, (term), a, b) // F(a) term F(b) term
                                        //                ^^^^

Further, any empty elements are dropped:

FOR_EACH_NONEMPTY_TERM(F, (term), a, EMPTY, b) // F(a) term F(b) term

This is more convenient in some cases, because FOR_EACH_NONEMPTY_TERM() expands to nothing when given an empty argument list, and it's often cumbersome to write a macro F that does the right thing even when given an empty argument.

One example is when __VA_ARGS__ may or may not be empty, and the results are embedded in a larger initializer:

#define SQUARE(x) ((x)*(x))

int my_array[] = {
        FOR_EACH_NONEMPTY_TERM(SQUARE, (,), FOO(...))
        FOR_EACH_NONEMPTY_TERM(SQUARE, (,), BAR(...))
        FOR_EACH_NONEMPTY_TERM(SQUARE, (,), BAZ(...))
};

This is more convenient than:

  1. figuring out whether the FOO, BAR, and BAZ expansions are empty and adding a comma manually (or not) between FOR_EACH() calls
  2. rewriting SQUARE so it reacts appropriately when "x" is empty (which would be necessary if e.g. FOO expands to nothing)
Parameters
FMacro to invoke on each nonempty element of the variable arguments
termTerminator (e.g. comma or semicolon) placed after each invocation of F. Must be in parentheses; this is required to enable providing a comma as separator.
...Variable argument list. The macro F is invoked as F(element) for each nonempty element in the list.

◆ GB

#define GB (   x)    (MB(x) << 10)

#include <zephyr/sys/util.h>

Number of bytes in x gibibytes.

◆ GENMASK

#define GENMASK (   h,
 
)     (((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))

#include <zephyr/sys/util.h>

Create a contiguous bitmask starting at bit position l and ending at position h.

◆ GENMASK64

#define GENMASK64 (   h,
 
)     (((~0ULL) - (1ULL << (l)) + 1) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))

#include <zephyr/sys/util.h>

Create a contiguous 64-bit bitmask starting at bit position l and ending at position h.

◆ GET_ARG_N

#define GET_ARG_N (   N,
  ... 
)    Z_GET_ARG_##N(__VA_ARGS__)

#include <zephyr/sys/util_macro.h>

Get nth argument from argument list.

Parameters
NArgument index to fetch. Counter from 1.
...Variable list of arguments from which one argument is returned.
Returns
Nth argument.

◆ GET_ARGS_LESS_N

#define GET_ARGS_LESS_N (   N,
  ... 
)    Z_GET_ARGS_LESS_##N(__VA_ARGS__)

#include <zephyr/sys/util_macro.h>

Strips n first arguments from the argument list.

Parameters
NNumber of arguments to discard.
...Variable list of arguments.
Returns
argument list without N first arguments.

◆ IDENTITY

#define IDENTITY (   V)    V

#include <zephyr/sys/util_macro.h>

Macro that expands to its argument.

This is useful in macros like FOR_EACH() when there is no transformation required on the list elements.

Parameters
Vany value

◆ IF_DISABLED

#define IF_DISABLED (   _flag,
  _code 
)     COND_CODE_1(_flag, (), _code)

#include <zephyr/sys/util_macro.h>

Insert code if _flag is not defined as 1.

This expands to nothing if _flag is defined and equal to 1; it expands to _code otherwise.

Example:

IF_DISABLED(CONFIG_FLAG, (uint32_t foo;))

If CONFIG_FLAG isn't defined or different than 1, this expands to:

uint32_t foo;

and to nothing otherwise.

IF_DISABLED does the opposite of IF_ENABLED.

Parameters
_flagevaluated flag
_coderesult if _flag does not expand to 1; must be in parentheses

◆ IF_ENABLED

#define IF_ENABLED (   _flag,
  _code 
)     COND_CODE_1(_flag, _code, ())

#include <zephyr/sys/util_macro.h>

Insert code if _flag is defined and equals 1.

Like COND_CODE_1(), this expands to _code if _flag is defined to 1; it expands to nothing otherwise.

Example:

IF_ENABLED(CONFIG_FLAG, (uint32_t foo;))

If CONFIG_FLAG is defined to 1, this expands to:

uint32_t foo;

and to nothing otherwise.

It can be considered as a more compact alternative to:

#if defined(CONFIG_FLAG) && (CONFIG_FLAG == 1)
uint32_t foo;
#endif
Parameters
_flagevaluated flag
_coderesult if _flag expands to 1; must be in parentheses

◆ IN_RANGE

#define IN_RANGE (   val,
  min,
  max 
)    ((val) >= (min) && (val) <= (max))

#include <zephyr/sys/util.h>

Checks if a value is within range.

Note
val is evaluated twice.
Parameters
valValue to be checked.
minLower bound (inclusive).
maxUpper bound (inclusive).
Return values
trueIf value is within range
falseIf the value is not within range

◆ INT_TO_POINTER

#define INT_TO_POINTER (   x)    ((void *) (intptr_t) (x))

#include <zephyr/sys/util.h>

Cast x, a signed integer, to a void*.

◆ IS_ALIGNED

#define IS_ALIGNED (   ptr,
  align 
)    (((uintptr_t)(ptr)) % (align) == 0)

#include <zephyr/sys/util.h>

Check if ptr is aligned to align alignment.

◆ IS_ARRAY

#define IS_ARRAY (   array)

#include <zephyr/sys/util.h>

Value:
!__builtin_types_compatible_p(__typeof__(array), \
__typeof__(&(array)[0])))
#define ZERO_OR_COMPILE_ERROR(cond)
0 if cond is true-ish; causes a compile error otherwise.
Definition: util.h:97

Zero if array has an array type, a compile error otherwise.

This macro is available only from C, not C++.

◆ IS_ARRAY_ELEMENT

#define IS_ARRAY_ELEMENT (   array,
  ptr 
)

#include <zephyr/sys/util.h>

Value:
((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) && \
POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]) && \
(POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) % sizeof((array)[0]) == 0)

Whether ptr is an element of array.

This macro can be seen as a slightly stricter version of PART_OF_ARRAY in that it also ensures that ptr is aligned to an array-element boundary of array.

In C, passing a pointer as array causes a compile error.

Parameters
arraythe array in question
ptrthe pointer to check
Returns
1 if ptr is part of array, 0 otherwise

◆ IS_BIT_MASK

#define IS_BIT_MASK (   m)    IS_SHIFTED_BIT_MASK(m, 0)

#include <zephyr/sys/util_macro.h>

Check if bits are set continuously from the LSB.

Parameters
mCheck whether the bits are set continuously from LSB.

◆ IS_EMPTY

#define IS_EMPTY (   ...)    Z_IS_EMPTY_(__VA_ARGS__)

#include <zephyr/sys/util_macro.h>

Check if a macro has a replacement expression.

If a is a macro defined to a nonempty value, this will return true, otherwise it will return false. It only works with defined macros, so an additional #ifdef test may be needed in some cases.

This macro may be used with COND_CODE_1() and COND_CODE_0() while processing __VA_ARGS__ to avoid processing empty arguments.

Example:

 #define EMPTY
 #define NON_EMPTY  1
 #undef  UNDEFINED
 IS_EMPTY(EMPTY)
 IS_EMPTY(NON_EMPTY)
 IS_EMPTY(UNDEFINED)
 #if defined(EMPTY) && IS_EMPTY(EMPTY) == true
 some_conditional_code
 #endif

In above examples, the invocations of IS_EMPTY(...) return true, false, and true; some_conditional_code is included.

Parameters
...macro to check for emptiness (may be __VA_ARGS__)

◆ IS_ENABLED

#define IS_ENABLED (   config_macro)    Z_IS_ENABLED1(config_macro)

#include <zephyr/sys/util_macro.h>

Check for macro definition in compiler-visible expressions.

This trick was pioneered in Linux as the config_enabled() macro. It has the effect of taking a macro value that may be defined to "1" or may not be defined at all and turning it into a literal expression that can be handled by the C compiler instead of just the preprocessor. It is often used with a CONFIG_FOO macro which may be defined to 1 via Kconfig, or left undefined.

That is, it works similarly to #if defined(CONFIG_FOO) except that its expansion is a C expression. Thus, much #ifdef usage can be replaced with equivalents like:

if (IS_ENABLED(CONFIG_FOO)) {
        do_something_with_foo
}

This is cleaner since the compiler can generate errors and warnings for do_something_with_foo even when CONFIG_FOO is undefined.

Note: Use of IS_ENABLED in a #if statement is discouraged as it doesn't provide any benefit vs plain #if defined()

Parameters
config_macroMacro to check
Returns
1 if config_macro is defined to 1, 0 otherwise (including if config_macro is not defined)

◆ IS_EQ

#define IS_EQ (   a,
 
)    Z_IS_EQ(a, b)

#include <zephyr/sys/util_macro.h>

Like a == b, but does evaluation and short-circuiting at C preprocessor time.

This however only works for integer literal from 0 to 4095.

◆ IS_POWER_OF_TWO

#define IS_POWER_OF_TWO (   x)    (((x) != 0U) && (((x) & ((x) - 1U)) == 0U))

#include <zephyr/sys/util_macro.h>

Check if a x is a power of two.

◆ IS_SHIFTED_BIT_MASK

#define IS_SHIFTED_BIT_MASK (   m,
  s 
)    (!(((m) >> (s)) & (((m) >> (s)) + 1U)))

#include <zephyr/sys/util_macro.h>

Check if bits are set continuously from the specified bit.

The macro is not dependent on the bit-width.

Parameters
mCheck whether the bits are set continuously or not.
sSpecify the lowest bit for that is continuously set bits.

◆ KB

#define KB (   x)    ((x) << 10)

#include <zephyr/sys/util.h>

Number of bytes in x kibibytes.

◆ KHZ

#define KHZ (   x)    ((x) * 1000)

#include <zephyr/sys/util.h>

Number of Hz in x kHz.

◆ LIST_DROP_EMPTY

#define LIST_DROP_EMPTY (   ...)     Z_LIST_DROP_FIRST(FOR_EACH(Z_LIST_NO_EMPTIES, (), __VA_ARGS__))

#include <zephyr/sys/util_macro.h>

Remove empty arguments from list.

During macro expansion, __VA_ARGS__ and other preprocessor generated lists may contain empty elements, e.g.:

 #define LIST ,a,b,,d,

Using EMPTY to show each empty element, LIST contains:

 EMPTY, a, b, EMPTY, d

When processing such lists, e.g. using FOR_EACH(), all empty elements will be processed, and may require filtering out. To make that process easier, it is enough to invoke LIST_DROP_EMPTY which will remove all empty elements.

Example:

 LIST_DROP_EMPTY(LIST)

expands to:

 a, b, d
Parameters
...list to be processed

◆ LISTIFY

#define LISTIFY (   LEN,
  F,
  sep,
  ... 
)    UTIL_CAT(Z_UTIL_LISTIFY_, LEN)(F, sep, __VA_ARGS__)

#include <zephyr/sys/util_macro.h>

Generates a sequence of code with configurable separator.

Example:

#define FOO(i, _) MY_PWM ## i
{ LISTIFY(PWM_COUNT, FOO, (,)) }

The above two lines expand to:

{ MY_PWM0 , MY_PWM1 }

Parameters
LENThe length of the sequence. Must be an integer literal less than 4095.
FA macro function that accepts at least two arguments: F(i, ...). F is called repeatedly in the expansion. Its first argument i is the index in the sequence, and the variable list of arguments passed to LISTIFY are passed through to F.
sepSeparator (e.g. comma or semicolon). Must be in parentheses; this is required to enable providing a comma as separator.
Note
Calling LISTIFY with undefined arguments has undefined behavior.

◆ LOG2

#define LOG2 (   x)    ((x) < 1 ? -1 : __z_log2(x))

#include <zephyr/sys/util.h>

Compute log2(x)

Note
This macro expands its argument multiple times (to permit use in constant expressions), which must not have side effects.
Parameters
xAn unsigned integral value to compute logarithm of (positive only)
Returns
log2(x) when 1 <= x <= max(x), -1 when x < 1

◆ LOG2CEIL

#define LOG2CEIL (   x)    ((x) < 1 ? 0 : __z_log2((x)-1) + 1)

#include <zephyr/sys/util.h>

Compute ceil(log2(x))

Note
This macro expands its argument multiple times (to permit use in constant expressions), which must not have side effects.
Parameters
xAn unsigned integral value
Returns
ceil(log2(x)) when 1 <= x <= max(type(x)), 0 when x < 1

◆ LSB_GET

#define LSB_GET (   value)    ((value) & -(value))

#include <zephyr/sys/util.h>

Extract the Least Significant Bit from value.

◆ MACRO_MAP_CAT

#define MACRO_MAP_CAT (   ...)    MACRO_MAP_CAT_(__VA_ARGS__)

#include <zephyr/sys/util_macro.h>

Mapping macro that pastes results together.

This is similar to FOR_EACH() in that it invokes a macro repeatedly on each element of __VA_ARGS__. However, unlike FOR_EACH(), MACRO_MAP_CAT() pastes the results together into a single token.

For example, with this macro FOO:

#define FOO(x) item_##x##_

MACRO_MAP_CAT(FOO, a, b, c), expands to the token:

item_a_item_b_item_c_
Parameters
...Macro to expand on each argument, followed by its arguments. (The macro should take exactly one argument.)
Returns
The results of expanding the macro on each argument, all pasted together

◆ MACRO_MAP_CAT_N

#define MACRO_MAP_CAT_N (   N,
  ... 
)    MACRO_MAP_CAT_N_(N, __VA_ARGS__)

#include <zephyr/sys/util_macro.h>

Mapping macro that pastes a fixed number of results together.

Similar to MACRO_MAP_CAT(), but expects a fixed number of arguments. If more arguments are given than are expected, the rest are ignored.

Parameters
NNumber of arguments to map
...Macro to expand on each argument, followed by its arguments. (The macro should take exactly one argument.)
Returns
The results of expanding the macro on each argument, all pasted together

◆ MAX

#define MAX (   a,
 
)    (((a) > (b)) ? (a) : (b))

#include <zephyr/sys/util.h>

Obtain the maximum of two values.

Note
Arguments are evaluated twice. Use Z_MAX for a GCC-only, single evaluation version
Parameters
aFirst value.
bSecond value.
Returns
Maximum value of a and b.

◆ MB

#define MB (   x)    (KB(x) << 10)

#include <zephyr/sys/util.h>

Number of bytes in x mebibytes.

◆ MHZ

#define MHZ (   x)    (KHZ(x) * 1000)

#include <zephyr/sys/util.h>

Number of Hz in x MHz.

◆ MIN

#define MIN (   a,
 
)    (((a) < (b)) ? (a) : (b))

#include <zephyr/sys/util.h>

Obtain the minimum of two values.

Note
Arguments are evaluated twice. Use Z_MIN for a GCC-only, single evaluation version
Parameters
aFirst value.
bSecond value.
Returns
Minimum value of a and b.

◆ NHPOT

#define NHPOT (   x)    ((x) < 1 ? 1 : ((x) > (1ULL<<63) ? 0 : 1ULL << LOG2CEIL(x)))

#include <zephyr/sys/util.h>

Compute next highest power of two.

Equivalent to 2^ceil(log2(x))

Note
This macro expands its argument multiple times (to permit use in constant expressions), which must not have side effects.
Parameters
xAn unsigned integral value
Returns
2^ceil(log2(x)) or 0 if 2^ceil(log2(x)) would saturate 64-bits

◆ NUM_VA_ARGS

#define NUM_VA_ARGS (   ...)     COND_CODE_1(IS_EMPTY(__VA_ARGS__), (0), (UTIL_INC(NUM_VA_ARGS_LESS_1(__VA_ARGS__))))

#include <zephyr/sys/util_macro.h>

Number of arguments in the variable arguments list.

Note
Supports up to 63 arguments.
Parameters
...List of arguments
Returns
Number of variadic arguments in the argument list

◆ NUM_VA_ARGS_LESS_1

#define NUM_VA_ARGS_LESS_1 (   ...)

#include <zephyr/sys/util_macro.h>

Value:
NUM_VA_ARGS_LESS_1_IMPL(__VA_ARGS__, 63, 62, 61, \
60, 59, 58, 57, 56, 55, 54, 53, 52, 51, \
50, 49, 48, 47, 46, 45, 44, 43, 42, 41, \
40, 39, 38, 37, 36, 35, 34, 33, 32, 31, \
30, 29, 28, 27, 26, 25, 24, 23, 22, 21, \
20, 19, 18, 17, 16, 15, 14, 13, 12, 11, \
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ~)
#define NUM_VA_ARGS_LESS_1_IMPL( _ignored, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, N,...)
Definition: util_internal.h:129

Number of arguments in the variable arguments list minus one.

Note
Supports up to 64 arguments.
Parameters
...List of arguments
Returns
Number of variadic arguments in the argument list, minus one

◆ PART_OF_ARRAY

#define PART_OF_ARRAY (   array,
  ptr 
)

#include <zephyr/sys/util.h>

Value:
((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) && \
POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]))

Check if a pointer ptr lies within array.

In C but not C++, this causes a compile error if array is not an array (e.g. if ptr and array are mixed up).

Parameters
arrayan array
ptra pointer
Returns
1 if ptr is part of array, 0 otherwise

◆ POINTER_TO_INT

#define POINTER_TO_INT (   x)    ((intptr_t) (x))

#include <zephyr/sys/util.h>

Cast x, a pointer, to a signed integer.

◆ POINTER_TO_UINT

#define POINTER_TO_UINT (   x)    ((uintptr_t) (x))

#include <zephyr/sys/util.h>

Cast x, a pointer, to an unsigned integer.

◆ REVERSE_ARGS

#define REVERSE_ARGS (   ...)     Z_FOR_EACH_ENGINE(Z_FOR_EACH_EXEC, (,), Z_BYPASS, _, __VA_ARGS__)

#include <zephyr/sys/util_macro.h>

Reverse arguments order.

Parameters
...Variable argument list.

◆ ROUND_DOWN

#define ROUND_DOWN (   x,
  align 
)     (((unsigned long)(x) / (unsigned long)(align)) * (unsigned long)(align))

#include <zephyr/sys/util.h>

Value of x rounded down to the previous multiple of align.

◆ ROUND_UP

#define ROUND_UP (   x,
  align 
)

#include <zephyr/sys/util.h>

Value:
((((unsigned long)(x) + ((unsigned long)(align) - 1)) / \
(unsigned long)(align)) * (unsigned long)(align))

Value of x rounded up to the next multiple of align.

◆ SAME_TYPE

#define SAME_TYPE (   a,
 
)    __builtin_types_compatible_p(__typeof__(a), __typeof__(b))

#include <zephyr/sys/util.h>

Validate if two entities have a compatible type.

Parameters
athe first entity to be compared
bthe second entity to be compared
Returns
1 if the two elements are compatible, 0 if they are not

◆ SIZEOF_FIELD

#define SIZEOF_FIELD (   type,
  member 
)    sizeof((((type *)0)->member))

#include <zephyr/sys/util.h>

Report the size of a struct field in bytes.

Parameters
typeThe structure containing the field of interest.
memberThe field to return the size of.
Returns
The field size.

◆ UINT_TO_POINTER

#define UINT_TO_POINTER (   x)    ((void *) (uintptr_t) (x))

#include <zephyr/sys/util.h>

Cast x, an unsigned integer, to a void*.

◆ UTIL_AND

#define UTIL_AND (   a,
 
)    COND_CODE_1(UTIL_BOOL(a), (b), (0))

#include <zephyr/sys/util_macro.h>

Like a && b, but does evaluation and short-circuiting at C preprocessor time.

This is not the same as the binary &&, however; in particular, a should expand to an integer literal 0 or 1. However, b can be any value.

This can be useful when b is an expression that would cause a build error when a is 0.

◆ UTIL_DEC

#define UTIL_DEC (   x)    UTIL_PRIMITIVE_CAT(Z_UTIL_DEC_, x)

#include <zephyr/sys/util_macro.h>

UTIL_DEC(x) for an integer literal x from 0 to 4095 expands to an integer literal whose value is x-1.

See also
UTIL_INC(x)

◆ UTIL_INC

#define UTIL_INC (   x)    UTIL_PRIMITIVE_CAT(Z_UTIL_INC_, x)

#include <zephyr/sys/util_macro.h>

UTIL_INC(x) for an integer literal x from 0 to 4095 expands to an integer literal whose value is x+1.

See also
UTIL_DEC(x)

◆ UTIL_OR

#define UTIL_OR (   a,
 
)    COND_CODE_1(UTIL_BOOL(a), (a), (b))

#include <zephyr/sys/util_macro.h>

Like a || b, but does evaluation and short-circuiting at C preprocessor time.

This is not the same as the binary || operator; in particular, a should expand to an integer literal 0 or 1. However, b can be any value.

This can be useful when b is an expression that would cause a build error when a is 1.

◆ UTIL_X2

#define UTIL_X2 (   y)    UTIL_PRIMITIVE_CAT(Z_UTIL_X2_, y)

#include <zephyr/sys/util_macro.h>

UTIL_X2(y) for an integer literal y from 0 to 4095 expands to an integer literal whose value is 2y.

◆ WAIT_FOR

#define WAIT_FOR (   expr,
  timeout,
  delay_stmt 
)

#include <zephyr/sys/util.h>

Value:
({ \
uint32_t _wf_cycle_count = k_us_to_cyc_ceil32(timeout); \
uint32_t _wf_start = k_cycle_get_32(); \
while (!(expr) && (_wf_cycle_count > (k_cycle_get_32() - _wf_start))) { \
delay_stmt; \
Z_SPIN_DELAY(10); \
} \
(expr); \
})
static uint32_t k_cycle_get_32(void)
Read the hardware clock.
Definition: kernel.h:1820
#define k_us_to_cyc_ceil32(t)
Convert microseconds to hardware cycles.
Definition: time_units.h:805
__UINT32_TYPE__ uint32_t
Definition: stdint.h:90

Wait for an expression to return true with a timeout.

Spin on an expression with a timeout and optional delay between iterations

Commonly needed when waiting on hardware to complete an asynchronous request to read/write/initialize/reset, but useful for any expression.

Parameters
exprTruth expression upon which to poll, e.g.: XYZREG & XYZREG_EN
timeoutTimeout to wait for in microseconds, e.g.: 1000 (1ms)
delay_stmtDelay statement to perform each poll iteration e.g.: NULL, k_yield(), k_msleep(1) or k_busy_wait(1)
Return values
exprAs a boolean return, if false then it has timed out.

◆ WB_DN

#define WB_DN (   x)    ROUND_DOWN(x, sizeof(void *))

#include <zephyr/sys/util.h>

Value of x rounded down to the previous word boundary.

◆ WB_UP

#define WB_UP (   x)    ROUND_UP(x, sizeof(void *))

#include <zephyr/sys/util.h>

Value of x rounded up to the next word boundary.

◆ WRITE_BIT

#define WRITE_BIT (   var,
  bit,
  set 
)     ((var) = (set) ? ((var) | BIT(bit)) : ((var) & ~BIT(bit)))

#include <zephyr/sys/util_macro.h>

Set or clear a bit depending on a boolean value.

The argument var is a variable whose value is written to as a side effect.

Parameters
varVariable to be altered
bitBit number
setif 0, clears bit in var; any other value sets bit

◆ ZERO_OR_COMPILE_ERROR

#define ZERO_OR_COMPILE_ERROR (   cond)    ((int) sizeof(char[1 - 2 * !(cond)]) - 1)

#include <zephyr/sys/util.h>

0 if cond is true-ish; causes a compile error otherwise.

Function Documentation

◆ arithmetic_shift_right()

static int64_t arithmetic_shift_right ( int64_t  value,
uint8_t  shift 
)
inlinestatic

#include <zephyr/sys/util.h>

Arithmetic shift right.

Parameters
valuevalue to shift
shiftnumber of bits to shift
Returns
value shifted right by shift; opened bit positions are filled with the sign bit

◆ bcd2bin()

static uint8_t bcd2bin ( uint8_t  bcd)
inlinestatic

#include <zephyr/sys/util.h>

Convert a binary coded decimal (BCD 8421) value to binary.

Parameters
bcdBCD 8421 value to convert.
Returns
Binary representation of input value.

◆ bin2bcd()

static uint8_t bin2bcd ( uint8_t  bin)
inlinestatic

#include <zephyr/sys/util.h>

Convert a binary value to binary coded decimal (BCD 8421).

Parameters
binBinary value to convert.
Returns
BCD 8421 representation of input value.

◆ bin2hex()

size_t bin2hex ( const uint8_t buf,
size_t  buflen,
char *  hex,
size_t  hexlen 
)

#include <zephyr/sys/util.h>

Convert a binary array into string representation.

Parameters
bufThe binary array to convert
buflenThe length of the binary array to convert
hexAddress of where to store the string representation.
hexlenSize of the storage area for string representation.
Returns
The length of the converted string, or 0 if an error occurred.

◆ bytecpy()

static void bytecpy ( void *  dst,
const void *  src,
size_t  size 
)
inlinestatic

#include <zephyr/sys/util.h>

byte by byte memcpy.

Copy size bytes of src into dest. This is guaranteed to be done byte by byte.

Parameters
dstPointer to the destination memory.
srcPointer to the source of the data.
sizeThe number of bytes to copy.

◆ byteswp()

static void byteswp ( void *  a,
void *  b,
size_t  size 
)
inlinestatic

#include <zephyr/sys/util.h>

byte by byte swap.

Swap size bytes between memory regions a and b. This is guaranteed to be done byte by byte.

Parameters
aPointer to the the first memory region.
bPointer to the the second memory region.
sizeThe number of bytes to swap.

◆ char2hex()

int char2hex ( char  c,
uint8_t x 
)

#include <zephyr/sys/util.h>

Convert a single character into a hexadecimal nibble.

Parameters
cThe character to convert
xThe address of storage for the converted number.
Returns
Zero on success or (negative) error code otherwise.

◆ hex2bin()

size_t hex2bin ( const char *  hex,
size_t  hexlen,
uint8_t buf,
size_t  buflen 
)

#include <zephyr/sys/util.h>

Convert a hexadecimal string into a binary array.

Parameters
hexThe hexadecimal string to convert
hexlenThe length of the hexadecimal string to convert.
bufAddress of where to store the binary data
buflenSize of the storage area for binary data
Returns
The length of the binary array, or 0 if an error occurred.

◆ hex2char()

int hex2char ( uint8_t  x,
char *  c 
)

#include <zephyr/sys/util.h>

Convert a single hexadecimal nibble into a character.

Parameters
cThe number to convert
xThe address of storage for the converted character.
Returns
Zero on success or (negative) error code otherwise.

◆ is_null_no_warn()

static ALWAYS_INLINE bool is_null_no_warn ( void *  p)
static

#include <zephyr/sys/util.h>

Is p equal to NULL?

Some macros may need to check their arguments against NULL to support multiple use-cases, but NULL checks can generate warnings if such a macro is used in contexts where that particular argument can never be NULL.

The warnings can be triggered if: a) all macros are expanded (e.g. when using CONFIG_COMPILER_SAVE_TEMPS=y) or b) tracking of macro expansions are turned off (-ftrack-macro-expansion=0)

The warnings can be circumvented by using this inline function for doing the NULL check within the macro. The compiler is still able to optimize the NULL check out at a later stage.

Parameters
pPointer to check
Returns
true if p is equal to NULL, false otherwise

◆ is_power_of_two()

static bool is_power_of_two ( unsigned int  x)
inlinestatic

#include <zephyr/sys/util.h>

Is x a power of two?

Parameters
xvalue to check
Returns
true if x is a power of two, false otherwise

◆ mem_xor_128()

static void mem_xor_128 ( uint8_t  dst[16],
const uint8_t  src1[16],
const uint8_t  src2[16] 
)
inlinestatic

#include <zephyr/sys/util.h>

XOR 128 bits.

Parameters
dstDestination of where to store result. Shall be 128 bits.
src1First source. Shall be 128 bits.
src2Second source. Shall be 128 bits.

◆ mem_xor_32()

static void mem_xor_32 ( uint8_t  dst[4],
const uint8_t  src1[4],
const uint8_t  src2[4] 
)
inlinestatic

#include <zephyr/sys/util.h>

XOR 32 bits.

Parameters
dstDestination of where to store result. Shall be 32 bits.
src1First source. Shall be 32 bits.
src2Second source. Shall be 32 bits.

◆ mem_xor_n()

static void mem_xor_n ( uint8_t dst,
const uint8_t src1,
const uint8_t src2,
size_t  len 
)
inlinestatic

#include <zephyr/sys/util.h>

XOR n bytes.

Parameters
dstDestination of where to store result. Shall be len bytes.
src1First source. Shall be len bytes.
src2Second source. Shall be len bytes.
lenNumber of bytes to XOR.

◆ sign_extend()

static int32_t sign_extend ( uint32_t  value,
uint8_t  index 
)
inlinestatic

#include <zephyr/sys/util.h>

Sign extend an 8, 16 or 32 bit value using the index bit as sign bit.

Parameters
valueThe value to sign expand.
index0 based bit index to sign bit (0 to 31)

◆ sign_extend_64()

static int64_t sign_extend_64 ( uint64_t  value,
uint8_t  index 
)
inlinestatic

#include <zephyr/sys/util.h>

Sign extend a 64 bit value using the index bit as sign bit.

Parameters
valueThe value to sign expand.
index0 based bit index to sign bit (0 to 63)

◆ u8_to_dec()

uint8_t u8_to_dec ( char *  buf,
uint8_t  buflen,
uint8_t  value 
)

#include <zephyr/sys/util.h>

Convert a uint8_t into a decimal string representation.

Convert a uint8_t value into its ASCII decimal string representation. The string is terminated if there is enough space in buf.

Parameters
bufAddress of where to store the string representation.
buflenSize of the storage area for string representation.
valueThe value to convert to decimal string
Returns
The length of the converted string (excluding terminator if any), or 0 if an error occurred.

◆ utf8_lcpy()

char * utf8_lcpy ( char *  dst,
const char *  src,
size_t  n 
)

#include <zephyr/sys/util.h>

Copies a UTF-8 encoded string from src to dst.

The resulting dst will always be NULL terminated if n is larger than 0, and the dst string will always be properly UTF-8 truncated.

Parameters
dstThe destination of the UTF-8 string.
srcThe source string
nThe size of the dst buffer. Maximum number of characters copied is n - 1. If 0 nothing will be done, and the dst will not be NULL terminated.
Returns
Pointer to the dst

◆ utf8_trunc()

char * utf8_trunc ( char *  utf8_str)

#include <zephyr/sys/util.h>

Properly truncate a NULL-terminated UTF-8 string.

Take a NULL-terminated UTF-8 string and ensure that if the string has been truncated (by setting the NULL terminator) earlier by other means, that the string ends with a properly formatted UTF-8 character (1-4 bytes).

Example: char test_str[] = "€€€"; char trunc_utf8[8]; printf("Original : %s\n", test_str); // €€€ strncpy(trunc_utf8, test_str, sizeof(trunc_utf8)); trunc_utf8[sizeof(trunc_utf8) - 1] = '\0'; printf("Bad : %s\n", trunc_utf8); // €€� utf8_trunc(trunc_utf8); printf("Truncated: %s\n", trunc_utf8); // €€

Parameters
utf8_strNULL-terminated string
Returns
Pointer to the utf8_str