LCOV - code coverage report
Current view: top level - zephyr/sys - util.h Coverage Total Hit
Test: new.info Lines: 100.0 % 70 70
Test Date: 2025-09-25 19:22:35

            Line data    Source code
       1            1 : /*
       2              :  * Copyright (c) 2011-2014, Wind River Systems, Inc.
       3              :  *
       4              :  * SPDX-License-Identifier: Apache-2.0
       5              :  */
       6              : 
       7              : /**
       8              :  * @file
       9              :  * @brief Misc utilities
      10              :  *
      11              :  * Misc utilities usable by the kernel and application code.
      12              :  */
      13              : 
      14              : #ifndef ZEPHYR_INCLUDE_SYS_UTIL_H_
      15              : #define ZEPHYR_INCLUDE_SYS_UTIL_H_
      16              : 
      17              : #include <zephyr/sys/util_macro.h>
      18              : #include <zephyr/toolchain.h>
      19              : 
      20              : /* needs to be outside _ASMLANGUAGE so 'true' and 'false' can turn
      21              :  * into '1' and '0' for asm or linker scripts
      22              :  */
      23              : #include <stdbool.h>
      24              : 
      25              : #ifndef _ASMLANGUAGE
      26              : 
      27              : #include <zephyr/sys/__assert.h>
      28              : #include <zephyr/types.h>
      29              : #include <stddef.h>
      30              : #include <stdint.h>
      31              : #include <string.h>
      32              : 
      33              : /** @brief Number of bits that make up a type */
      34            1 : #define NUM_BITS(t) (sizeof(t) * BITS_PER_BYTE)
      35              : 
      36              : #ifdef __cplusplus
      37              : extern "C" {
      38              : #endif
      39              : 
      40              : /**
      41              :  * @defgroup sys-util Utility Functions
      42              :  * @since 2.4
      43              :  * @version 0.1.0
      44              :  * @ingroup utilities
      45              :  * @{
      46              :  */
      47              : 
      48              : /** @brief Cast @p x, a pointer, to an unsigned integer. */
      49            1 : #define POINTER_TO_UINT(x) ((uintptr_t) (x))
      50              : /** @brief Cast @p x, an unsigned integer, to a <tt>void*</tt>. */
      51            1 : #define UINT_TO_POINTER(x) ((void *) (uintptr_t) (x))
      52              : /** @brief Cast @p x, a pointer, to a signed integer. */
      53            1 : #define POINTER_TO_INT(x)  ((intptr_t) (x))
      54              : /** @brief Cast @p x, a signed integer, to a <tt>void*</tt>. */
      55            1 : #define INT_TO_POINTER(x)  ((void *) (intptr_t) (x))
      56              : 
      57              : #if !(defined(__CHAR_BIT__) && defined(__SIZEOF_LONG__) && defined(__SIZEOF_LONG_LONG__))
      58              : #       error Missing required predefined macros for BITS_PER_LONG calculation
      59              : #endif
      60              : 
      61              : /** Number of bits in a byte. */
      62            1 : #define BITS_PER_BYTE (__CHAR_BIT__)
      63              : 
      64              : /** Number of bits in a nibble. */
      65            1 : #define BITS_PER_NIBBLE (__CHAR_BIT__ / 2)
      66              : 
      67              : /** Number of nibbles in a byte. */
      68            1 : #define NIBBLES_PER_BYTE (BITS_PER_BYTE / BITS_PER_NIBBLE)
      69              : 
      70              : /** Number of bits in a long int. */
      71            1 : #define BITS_PER_LONG   (__CHAR_BIT__ * __SIZEOF_LONG__)
      72              : 
      73              : /** Number of bits in a long long int. */
      74            1 : #define BITS_PER_LONG_LONG      (__CHAR_BIT__ * __SIZEOF_LONG_LONG__)
      75              : 
      76              : /**
      77              :  * @brief Create a contiguous bitmask starting at bit position @p l
      78              :  *        and ending at position @p h.
      79              :  */
      80            1 : #define GENMASK(h, l) \
      81              :         (((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
      82              : 
      83              : /**
      84              :  * @brief Create a contiguous 64-bit bitmask starting at bit position @p l
      85              :  *        and ending at position @p h.
      86              :  */
      87            1 : #define GENMASK64(h, l) \
      88              :         (((~0ULL) - (1ULL << (l)) + 1) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))
      89              : 
      90              : /** @brief 0 if @p cond is true-ish; causes a compile error otherwise. */
      91            1 : #define ZERO_OR_COMPILE_ERROR(cond) ((int) sizeof(char[1 - (2 * !(cond))]) - 1)
      92              : 
      93              : #if defined(__cplusplus)
      94              : 
      95              : /* The built-in function used below for type checking in C is not
      96              :  * supported by GNU C++.
      97              :  */
      98              : #define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
      99              : 
     100              : #else /* __cplusplus */
     101              : 
     102              : /**
     103              :  * @brief Zero if @p array has an array type, a compile error otherwise
     104              :  *
     105              :  * This macro is available only from C, not C++.
     106              :  */
     107            1 : #define IS_ARRAY(array) \
     108              :         ZERO_OR_COMPILE_ERROR( \
     109              :                 !__builtin_types_compatible_p(__typeof__(array), \
     110              :                                               __typeof__(&(array)[0])))
     111              : 
     112              : /**
     113              :  * @brief Number of elements in the given @p array
     114              :  *
     115              :  * In C++, due to language limitations, this will accept as @p array
     116              :  * any type that implements <tt>operator[]</tt>. The results may not be
     117              :  * particularly meaningful in this case.
     118              :  *
     119              :  * In C, passing a pointer as @p array causes a compile error.
     120              :  */
     121            1 : #define ARRAY_SIZE(array) \
     122              :         ((size_t) (IS_ARRAY(array) + (sizeof(array) / sizeof((array)[0]))))
     123              : 
     124              : #endif /* __cplusplus */
     125              : 
     126              : /**
     127              :  * @brief Declare a flexible array member.
     128              :  *
     129              :  * This macro declares a flexible array member in a struct. The member
     130              :  * is named @p name and has type @p type.
     131              :  *
     132              :  * Since C99, flexible arrays are part of the C standard, but for historical
     133              :  * reasons many places still use an older GNU extension that is declare
     134              :  * zero length arrays.
     135              :  *
     136              :  * Although zero length arrays are flexible arrays, we can't blindly
     137              :  * replace [0] with [] because of some syntax limitations. This macro
     138              :  * workaround these limitations.
     139              :  *
     140              :  * It is specially useful for cases where flexible arrays are
     141              :  * used in unions or are not the last element in the struct.
     142              :  */
     143            1 : #define FLEXIBLE_ARRAY_DECLARE(type, name) \
     144              :         struct { \
     145              :                 struct { } __unused_##name; \
     146              :                 type name[]; \
     147              :         }
     148              : 
     149              : /**
     150              :  * @brief Whether @p ptr is an element of @p array
     151              :  *
     152              :  * This macro can be seen as a slightly stricter version of @ref PART_OF_ARRAY
     153              :  * in that it also ensures that @p ptr is aligned to an array-element boundary
     154              :  * of @p array.
     155              :  *
     156              :  * In C, passing a pointer as @p array causes a compile error.
     157              :  *
     158              :  * @param array the array in question
     159              :  * @param ptr the pointer to check
     160              :  *
     161              :  * @return 1 if @p ptr is part of @p array, 0 otherwise
     162              :  */
     163            1 : #define IS_ARRAY_ELEMENT(array, ptr)                                                               \
     164              :         ((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) &&                          \
     165              :          POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]) &&                    \
     166              :          (POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) % sizeof((array)[0]) == 0)
     167              : 
     168              : /**
     169              :  * @brief Index of @p ptr within @p array
     170              :  *
     171              :  * With `CONFIG_ASSERT=y`, this macro will trigger a runtime assertion
     172              :  * when @p ptr does not fall into the range of @p array or when @p ptr
     173              :  * is not aligned to an array-element boundary of @p array.
     174              :  *
     175              :  * In C, passing a pointer as @p array causes a compile error.
     176              :  *
     177              :  * @param array the array in question
     178              :  * @param ptr pointer to an element of @p array
     179              :  *
     180              :  * @return the array index of @p ptr within @p array, on success
     181              :  */
     182            1 : #define ARRAY_INDEX(array, ptr)                                                                    \
     183              :         ({                                                                                         \
     184              :                 __ASSERT_NO_MSG(IS_ARRAY_ELEMENT(array, ptr));                                     \
     185              :                 (__typeof__((array)[0]) *)(ptr) - (array);                                         \
     186              :         })
     187              : 
     188              : /**
     189              :  * @brief Check if a pointer @p ptr lies within @p array.
     190              :  *
     191              :  * In C but not C++, this causes a compile error if @p array is not an array
     192              :  * (e.g. if @p ptr and @p array are mixed up).
     193              :  *
     194              :  * @param array an array
     195              :  * @param ptr a pointer
     196              :  * @return 1 if @p ptr is part of @p array, 0 otherwise
     197              :  */
     198            1 : #define PART_OF_ARRAY(array, ptr)                                                                  \
     199              :         ((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) &&                                \
     200              :          POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]))
     201              : 
     202              : /**
     203              :  * @brief Array-index of @p ptr within @p array, rounded down
     204              :  *
     205              :  * This macro behaves much like @ref ARRAY_INDEX with the notable
     206              :  * difference that it accepts any @p ptr in the range of @p array rather than
     207              :  * exclusively a @p ptr aligned to an array-element boundary of @p array.
     208              :  *
     209              :  * With `CONFIG_ASSERT=y`, this macro will trigger a runtime assertion
     210              :  * when @p ptr does not fall into the range of @p array.
     211              :  *
     212              :  * In C, passing a pointer as @p array causes a compile error.
     213              :  *
     214              :  * @param array the array in question
     215              :  * @param ptr pointer to an element of @p array
     216              :  *
     217              :  * @return the array index of @p ptr within @p array, on success
     218              :  */
     219            1 : #define ARRAY_INDEX_FLOOR(array, ptr)                                                              \
     220              :         ({                                                                                         \
     221              :                 __ASSERT_NO_MSG(PART_OF_ARRAY(array, ptr));                                        \
     222              :                 (POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) / sizeof((array)[0]);              \
     223              :         })
     224              : 
     225              : /**
     226              :  * @brief Iterate over members of an array using an index variable
     227              :  *
     228              :  * @param array the array in question
     229              :  * @param idx name of array index variable
     230              :  */
     231            1 : #define ARRAY_FOR_EACH(array, idx) for (size_t idx = 0; (idx) < ARRAY_SIZE(array); ++(idx))
     232              : 
     233              : /**
     234              :  * @brief Iterate over members of an array using a pointer
     235              :  *
     236              :  * @param array the array in question
     237              :  * @param ptr pointer to an element of @p array
     238              :  */
     239            1 : #define ARRAY_FOR_EACH_PTR(array, ptr)                                                             \
     240              :         for (__typeof__(*(array)) *ptr = (array); (size_t)((ptr) - (array)) < ARRAY_SIZE(array);   \
     241              :              ++(ptr))
     242              : 
     243              : /**
     244              :  * @brief Validate if two entities have a compatible type
     245              :  *
     246              :  * @param a the first entity to be compared
     247              :  * @param b the second entity to be compared
     248              :  * @return 1 if the two elements are compatible, 0 if they are not
     249              :  */
     250            1 : #define SAME_TYPE(a, b) __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
     251              : 
     252              : /**
     253              :  * @brief Validate CONTAINER_OF parameters, only applies to C mode.
     254              :  */
     255              : #ifndef __cplusplus
     256            1 : #define CONTAINER_OF_VALIDATE(ptr, type, field)               \
     257              :         BUILD_ASSERT(SAME_TYPE(*(ptr), ((type *)0)->field) || \
     258              :                      SAME_TYPE(*(ptr), void),                 \
     259              :                      "pointer type mismatch in CONTAINER_OF");
     260              : #else
     261              : #define CONTAINER_OF_VALIDATE(ptr, type, field)
     262              : #endif
     263              : 
     264              : /**
     265              :  * @brief Get a pointer to a structure containing the element
     266              :  *
     267              :  * Example:
     268              :  *
     269              :  *      struct foo {
     270              :  *              int bar;
     271              :  *      };
     272              :  *
     273              :  *      struct foo my_foo;
     274              :  *      int *ptr = &my_foo.bar;
     275              :  *
     276              :  *      struct foo *container = CONTAINER_OF(ptr, struct foo, bar);
     277              :  *
     278              :  * Above, @p container points at @p my_foo.
     279              :  *
     280              :  * @param ptr pointer to a structure element
     281              :  * @param type name of the type that @p ptr is an element of
     282              :  * @param field the name of the field within the struct @p ptr points to
     283              :  * @return a pointer to the structure that contains @p ptr
     284              :  */
     285            1 : #define CONTAINER_OF(ptr, type, field)                               \
     286              :         ({                                                           \
     287              :                 CONTAINER_OF_VALIDATE(ptr, type, field)              \
     288              :                 ((type *)(((char *)(ptr)) - offsetof(type, field))); \
     289              :         })
     290              : 
     291              : /**
     292              :  * @brief Report the size of a struct field in bytes.
     293              :  *
     294              :  * @param type The structure containing the field of interest.
     295              :  * @param member The field to return the size of.
     296              :  *
     297              :  * @return The field size.
     298              :  */
     299            1 : #define SIZEOF_FIELD(type, member) sizeof((((type *)0)->member))
     300              : 
     301              : /**
     302              :  * @brief Concatenate input arguments
     303              :  *
     304              :  * Concatenate provided tokens into a combined token during the preprocessor pass.
     305              :  * This can be used to, for ex., build an identifier out of multiple parts,
     306              :  * where one of those parts may be, for ex, a number, another macro, or a macro argument.
     307              :  *
     308              :  * @param ... Tokens to concatencate
     309              :  *
     310              :  * @return Concatenated token.
     311              :  */
     312            1 : #define CONCAT(...) \
     313              :         UTIL_CAT(_CONCAT_, NUM_VA_ARGS_LESS_1(__VA_ARGS__))(__VA_ARGS__)
     314              : 
     315              : /**
     316              :  * @brief Check if @p ptr is aligned to @p align alignment
     317              :  */
     318            1 : #define IS_ALIGNED(ptr, align) (((uintptr_t)(ptr)) % (align) == 0)
     319              : 
     320              : /**
     321              :  * @brief Value of @p x rounded up to the next multiple of @p align.
     322              :  */
     323            1 : #define ROUND_UP(x, align)                                   \
     324              :         ((((unsigned long)(x) + ((unsigned long)(align) - 1)) / \
     325              :           (unsigned long)(align)) * (unsigned long)(align))
     326              : 
     327              : /**
     328              :  * @brief Value of @p x rounded down to the previous multiple of @p align.
     329              :  */
     330            1 : #define ROUND_DOWN(x, align)                                 \
     331              :         (((unsigned long)(x) / (unsigned long)(align)) * (unsigned long)(align))
     332              : 
     333              : /** @brief Value of @p x rounded up to the next word boundary. */
     334            1 : #define WB_UP(x) ROUND_UP(x, sizeof(void *))
     335              : 
     336              : /** @brief Value of @p x rounded down to the previous word boundary. */
     337            1 : #define WB_DN(x) ROUND_DOWN(x, sizeof(void *))
     338              : 
     339              : /**
     340              :  * @brief Divide and round up.
     341              :  *
     342              :  * Example:
     343              :  * @code{.c}
     344              :  * DIV_ROUND_UP(1, 2); // 1
     345              :  * DIV_ROUND_UP(3, 2); // 2
     346              :  * @endcode
     347              :  *
     348              :  * @param n Numerator.
     349              :  * @param d Denominator.
     350              :  *
     351              :  * @return The result of @p n / @p d, rounded up.
     352              :  */
     353            1 : #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
     354              : 
     355              : /**
     356              :  * @brief Divide and round to the nearest integer.
     357              :  *
     358              :  * Example:
     359              :  * @code{.c}
     360              :  * DIV_ROUND_CLOSEST(5, 2); // 3
     361              :  * DIV_ROUND_CLOSEST(5, -2); // -3
     362              :  * DIV_ROUND_CLOSEST(5, 3); // 2
     363              :  * @endcode
     364              :  *
     365              :  * @param n Numerator.
     366              :  * @param d Denominator.
     367              :  *
     368              :  * @return The result of @p n / @p d, rounded to the nearest integer.
     369              :  */
     370            1 : #define DIV_ROUND_CLOSEST(n, d)                                                                    \
     371              :         (((((__typeof__(n))-1) < 0) && (((__typeof__(d))-1) < 0) && ((n) < 0) ^ ((d) < 0))         \
     372              :                  ? ((n) - ((d) / 2)) / (d)                                                         \
     373              :                  : ((n) + ((d) / 2)) / (d))
     374              : 
     375              : #ifndef MAX
     376              : /**
     377              :  * @brief Obtain the maximum of two values.
     378              :  *
     379              :  * @note Arguments are evaluated twice. Use Z_MAX for a GCC-only, single
     380              :  * evaluation version
     381              :  *
     382              :  * @param a First value.
     383              :  * @param b Second value.
     384              :  *
     385              :  * @returns Maximum value of @p a and @p b.
     386              :  */
     387            1 : #define MAX(a, b) (((a) > (b)) ? (a) : (b))
     388              : #endif
     389              : 
     390              : #ifndef MIN
     391              : /**
     392              :  * @brief Obtain the minimum of two values.
     393              :  *
     394              :  * @note Arguments are evaluated twice. Use Z_MIN for a GCC-only, single
     395              :  * evaluation version
     396              :  *
     397              :  * @param a First value.
     398              :  * @param b Second value.
     399              :  *
     400              :  * @returns Minimum value of @p a and @p b.
     401              :  */
     402            1 : #define MIN(a, b) (((a) < (b)) ? (a) : (b))
     403              : #endif
     404              : 
     405              : #ifndef MAX_FROM_LIST
     406              : /**
     407              :  * @brief Returns the maximum of a single value (base case).
     408              :  * @param a The value.
     409              :  * @returns The value `a`.
     410              :  */
     411              : #define Z_MAX_1(a) a
     412              : 
     413              : /**
     414              :  * @brief Returns the maximum of two values.
     415              :  *
     416              :  * @note Arguments are evaluated multiple times.
     417              :  *
     418              :  * @param a First value.
     419              :  * @param b Second value.
     420              :  * @returns Maximum value of @p a and @p b.
     421              :  */
     422              : #define Z_MAX_2(a, b) ((a) > (b) ? (a) : (b))
     423              : 
     424              : /**
     425              :  * @brief Returns the maximum of three values.
     426              :  * @note Arguments may be evaluated multiple times.
     427              :  * @param a First value.
     428              :  * @param b Second value.
     429              :  * @param c Third value.
     430              :  * @returns Maximum value of @p a, @p b, and @p c.
     431              :  */
     432              : #define Z_MAX_3(a, b, c) Z_MAX_2(a, Z_MAX_2(b, c))
     433              : 
     434              : /**
     435              :  * @brief Returns the maximum of four values.
     436              :  * @note Arguments may be evaluated multiple times.
     437              :  * @param a First value.
     438              :  * @param b Second value.
     439              :  * @param c Third value.
     440              :  * @param d Fourth value.
     441              :  * @returns Maximum value of @p a, @p b, @p c, and @p d.
     442              :  */
     443              : #define Z_MAX_4(a, b, c, d) Z_MAX_2(Z_MAX_2(a, b), Z_MAX_2(c, d))
     444              : 
     445              : /**
     446              :  * @brief Returns the maximum of five values.
     447              :  * @note Arguments may be evaluated multiple times.
     448              :  */
     449              : #define Z_MAX_5(a, b, c, d, e) Z_MAX_2(Z_MAX_4(a, b, c, d), e)
     450              : 
     451              : /**
     452              :  * @brief Returns the maximum of six values.
     453              :  * @note Arguments may be evaluated multiple times.
     454              :  */
     455              : #define Z_MAX_6(a, b, c, d, e, f) Z_MAX_2(Z_MAX_5(a, b, c, d, e), f)
     456              : 
     457              : /**
     458              :  * @brief Returns the maximum of seven values.
     459              :  * @note Arguments may be evaluated multiple times.
     460              :  */
     461              : #define Z_MAX_7(a, b, c, d, e, f, g) Z_MAX_2(Z_MAX_6(a, b, c, d, e, f), g)
     462              : 
     463              : /**
     464              :  * @brief Returns the maximum of eight values.
     465              :  * @note Arguments may be evaluated multiple times.
     466              :  */
     467              : #define Z_MAX_8(a, b, c, d, e, f, g, h) Z_MAX_2(Z_MAX_7(a, b, c, d, e, f, g), h)
     468              : 
     469              : /**
     470              :  * @brief Returns the maximum of nine values.
     471              :  * @note Arguments may be evaluated multiple times.
     472              :  */
     473              : #define Z_MAX_9(a, b, c, d, e, f, g, h, i) Z_MAX_2(Z_MAX_8(a, b, c, d, e, f, g, h), i)
     474              : 
     475              : /**
     476              :  * @brief Returns the maximum of ten values.
     477              :  * @note Arguments may be evaluated multiple times.
     478              :  */
     479              : #define Z_MAX_10(a, b, c, d, e, f, g, h, i, j) Z_MAX_2(Z_MAX_9(a, b, c, d, e, f, g, h, i), j)
     480              : 
     481              : /**
     482              :  * @brief Helper macro to select the correct MAX_N macro.
     483              :  *
     484              :  * This macro uses the argument-counting trick to pick the correct
     485              :  * `Z_MAX_N` macro name from the arguments provided to `MAX_FROM_LIST`.
     486              :  * The 10th argument (or 11th including `NAME`) effectively becomes the
     487              :  * macro name to use.
     488              :  *
     489              :  * @param _1 Positional argument 1.
     490              :  * @param _2 Positional argument 2.
     491              :  * @param _3 Positional argument 3.
     492              :  * @param _4 Positional argument 4.
     493              :  * @param _5 Positional argument 5.
     494              :  * @param _6 Positional argument 6.
     495              :  * @param _7 Positional argument 7.
     496              :  * @param _8 Positional argument 8.
     497              :  * @param _9 Positional argument 9.
     498              :  * @param _10 Positional argument 10.
     499              :  * @param NAME The macro name to be selected.
     500              :  * @param ... Additional arguments.
     501              :  * @returns The selected macro name `NAME`.
     502              :  */
     503              : #define Z_GET_MAX_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, NAME, ...) NAME
     504              : 
     505              : /**
     506              :  * @brief Finds the maximum value from a list of 1 to 10 arguments.
     507              :  *
     508              :  * Dispatches to the appropriate internal `Z_MAX_N` macro based on the number of
     509              :  * arguments provided.
     510              :  *
     511              :  * Example Usage:
     512              :  *   MAX_FROM_LIST(1, 5, 2)
     513              :  *   MAX_FROM_LIST(10)
     514              :  *
     515              :  * @note Arguments may be evaluated multiple times by the underlying
     516              :  *       `Z_MAX_N` macros. Avoid expressions with side effects.
     517              :  *
     518              :  * @param ... A list of 1 to 10 values to compare.
     519              :  * @returns The maximum value among the arguments.
     520              :  */
     521            1 : #define MAX_FROM_LIST(...)                                                                         \
     522              :         Z_GET_MAX_MACRO(__VA_ARGS__, Z_MAX_10, Z_MAX_9, Z_MAX_8, Z_MAX_7, Z_MAX_6, Z_MAX_5,        \
     523              :                         Z_MAX_4, Z_MAX_3, Z_MAX_2, Z_MAX_1)(__VA_ARGS__)
     524              : #endif
     525              : 
     526              : #ifndef CLAMP
     527              : /**
     528              :  * @brief Clamp a value to a given range.
     529              :  *
     530              :  * @note Arguments are evaluated multiple times. Use Z_CLAMP for a GCC-only,
     531              :  * single evaluation version.
     532              :  *
     533              :  * @param val Value to be clamped.
     534              :  * @param low Lowest allowed value (inclusive).
     535              :  * @param high Highest allowed value (inclusive).
     536              :  *
     537              :  * @returns Clamped value.
     538              :  */
     539            1 : #define CLAMP(val, low, high) (((val) <= (low)) ? (low) : MIN(val, high))
     540              : #endif
     541              : 
     542              : /**
     543              :  * @brief Checks if a value is within range.
     544              :  *
     545              :  * @note @p val is evaluated twice.
     546              :  *
     547              :  * @param val Value to be checked.
     548              :  * @param min Lower bound (inclusive).
     549              :  * @param max Upper bound (inclusive).
     550              :  *
     551              :  * @retval true If value is within range
     552              :  * @retval false If the value is not within range
     553              :  */
     554            1 : #define IN_RANGE(val, min, max) ((val) >= (min) && (val) <= (max))
     555              : 
     556              : /**
     557              :  * Find number of contiguous bits which are not set in the bit mask (32 bits).
     558              :  *
     559              :  * It is possible to return immediately when requested number of bits is found or
     560              :  * iterate over whole mask and return the best fit (smallest from available options).
     561              :  *
     562              :  * @param[in] mask 32 bit mask.
     563              :  * @param[in] num_bits Number of bits to find.
     564              :  * @param[in] total_bits Total number of LSB bits that can be used in the mask.
     565              :  * @param[in] first_match If true returns when first match is found, else returns the best fit.
     566              :  *
     567              :  * @retval -1 Contiguous bits not found.
     568              :  * @retval non-negative Starting index of the bits group.
     569              :  */
     570            1 : int bitmask_find_gap(uint32_t mask, size_t num_bits, size_t total_bits, bool first_match);
     571              : 
     572              : /**
     573              :  * @brief Is @p x a power of two?
     574              :  * @param x value to check
     575              :  * @return true if @p x is a power of two, false otherwise
     576              :  */
     577            1 : static inline bool is_power_of_two(unsigned int x)
     578              : {
     579              :         return IS_POWER_OF_TWO(x);
     580              : }
     581              : 
     582              : /**
     583              :  * @brief Is @p p equal to ``NULL``?
     584              :  *
     585              :  * Some macros may need to check their arguments against NULL to support
     586              :  * multiple use-cases, but NULL checks can generate warnings if such a macro
     587              :  * is used in contexts where that particular argument can never be NULL.
     588              :  *
     589              :  * The warnings can be triggered if:
     590              :  * a) all macros are expanded (e.g. when using CONFIG_COMPILER_SAVE_TEMPS=y)
     591              :  * or
     592              :  * b) tracking of macro expansions are turned off (-ftrack-macro-expansion=0)
     593              :  *
     594              :  * The warnings can be circumvented by using this inline function for doing
     595              :  * the NULL check within the macro. The compiler is still able to optimize the
     596              :  * NULL check out at a later stage.
     597              :  *
     598              :  * @param p Pointer to check
     599              :  * @return true if @p p is equal to ``NULL``, false otherwise
     600              :  */
     601            1 : static ALWAYS_INLINE bool is_null_no_warn(void *p)
     602              : {
     603              :         return p == NULL;
     604              : }
     605              : 
     606              : /**
     607              :  * @brief Arithmetic shift right
     608              :  * @param value value to shift
     609              :  * @param shift number of bits to shift
     610              :  * @return @p value shifted right by @p shift; opened bit positions are
     611              :  *         filled with the sign bit
     612              :  */
     613            1 : static inline int64_t arithmetic_shift_right(int64_t value, uint8_t shift)
     614              : {
     615              :         int64_t sign_ext;
     616              : 
     617              :         if (shift == 0U) {
     618              :                 return value;
     619              :         }
     620              : 
     621              :         /* extract sign bit */
     622              :         sign_ext = (value >> 63) & 1;
     623              : 
     624              :         /* make all bits of sign_ext be the same as the value's sign bit */
     625              :         sign_ext = -sign_ext;
     626              : 
     627              :         /* shift value and fill opened bit positions with sign bit */
     628              :         return (value >> shift) | (sign_ext << (64 - shift));
     629              : }
     630              : 
     631              : /**
     632              :  * @brief byte by byte memcpy.
     633              :  *
     634              :  * Copy `size` bytes of `src` into `dest`. This is guaranteed to be done byte by byte.
     635              :  *
     636              :  * @param dst Pointer to the destination memory.
     637              :  * @param src Pointer to the source of the data.
     638              :  * @param size The number of bytes to copy.
     639              :  */
     640            1 : static inline void bytecpy(void *dst, const void *src, size_t size)
     641              : {
     642              :         size_t i;
     643              : 
     644              :         for (i = 0; i < size; ++i) {
     645              :                 ((volatile uint8_t *)dst)[i] = ((volatile const uint8_t *)src)[i];
     646              :         }
     647              : }
     648              : 
     649              : /**
     650              :  * @brief byte by byte swap.
     651              :  *
     652              :  * Swap @a size bytes between memory regions @a a and @a b. This is
     653              :  * guaranteed to be done byte by byte.
     654              :  *
     655              :  * @param a Pointer to the first memory region.
     656              :  * @param b Pointer to the second memory region.
     657              :  * @param size The number of bytes to swap.
     658              :  */
     659            1 : static inline void byteswp(void *a, void *b, size_t size)
     660              : {
     661              :         uint8_t t;
     662              :         uint8_t *aa = (uint8_t *)a;
     663              :         uint8_t *bb = (uint8_t *)b;
     664              : 
     665              :         for (; size > 0; --size) {
     666              :                 t = *aa;
     667              :                 *aa++ = *bb;
     668              :                 *bb++ = t;
     669              :         }
     670              : }
     671              : 
     672              : /**
     673              :  * @brief      Convert a single character into a hexadecimal nibble.
     674              :  *
     675              :  * @param c     The character to convert
     676              :  * @param x     The address of storage for the converted number.
     677              :  *
     678              :  *  @return Zero on success or (negative) error code otherwise.
     679              :  */
     680            1 : int char2hex(char c, uint8_t *x);
     681              : 
     682              : /**
     683              :  * @brief      Convert a single hexadecimal nibble into a character.
     684              :  *
     685              :  * @param c     The number to convert
     686              :  * @param x     The address of storage for the converted character.
     687              :  *
     688              :  *  @return Zero on success or (negative) error code otherwise.
     689              :  */
     690            1 : int hex2char(uint8_t x, char *c);
     691              : 
     692              : /**
     693              :  * @brief      Convert a binary array into string representation.
     694              :  *
     695              :  * @param buf     The binary array to convert
     696              :  * @param buflen  The length of the binary array to convert
     697              :  * @param hex     Address of where to store the string representation.
     698              :  * @param hexlen  Size of the storage area for string representation.
     699              :  *
     700              :  * @return     The length of the converted string, or 0 if an error occurred.
     701              :  */
     702            1 : size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen);
     703              : 
     704              : /**
     705              :  * @brief      Convert a hexadecimal string into a binary array.
     706              :  *
     707              :  * @param hex     The hexadecimal string to convert
     708              :  * @param hexlen  The length of the hexadecimal string to convert.
     709              :  * @param buf     Address of where to store the binary data
     710              :  * @param buflen  Size of the storage area for binary data
     711              :  *
     712              :  * @return     The length of the binary array, or 0 if an error occurred.
     713              :  */
     714            1 : size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen);
     715              : 
     716              : /**
     717              :  * @brief Convert a binary coded decimal (BCD 8421) value to binary.
     718              :  *
     719              :  * @param bcd BCD 8421 value to convert.
     720              :  *
     721              :  * @return Binary representation of input value.
     722              :  */
     723            1 : static inline uint8_t bcd2bin(uint8_t bcd)
     724              : {
     725              :         return ((10 * (bcd >> 4)) + (bcd & 0x0F));
     726              : }
     727              : 
     728              : /**
     729              :  * @brief Convert a binary value to binary coded decimal (BCD 8421).
     730              :  *
     731              :  * @param bin Binary value to convert.
     732              :  *
     733              :  * @return BCD 8421 representation of input value.
     734              :  */
     735            1 : static inline uint8_t bin2bcd(uint8_t bin)
     736              : {
     737              :         return (((bin / 10) << 4) | (bin % 10));
     738              : }
     739              : 
     740              : /**
     741              :  * @brief      Convert a uint8_t into a decimal string representation.
     742              :  *
     743              :  * Convert a uint8_t value into its ASCII decimal string representation.
     744              :  * The string is terminated if there is enough space in buf.
     745              :  *
     746              :  * @param buf     Address of where to store the string representation.
     747              :  * @param buflen  Size of the storage area for string representation.
     748              :  * @param value   The value to convert to decimal string
     749              :  *
     750              :  * @return     The length of the converted string (excluding terminator if
     751              :  *             any), or 0 if an error occurred.
     752              :  */
     753            1 : uint8_t u8_to_dec(char *buf, uint8_t buflen, uint8_t value);
     754              : 
     755              : /**
     756              :  * @brief Sign extend an 8, 16 or 32 bit value using the index bit as sign bit.
     757              :  *
     758              :  * @param value The value to sign expand.
     759              :  * @param index 0 based bit index to sign bit (0 to 31)
     760              :  */
     761            1 : static inline int32_t sign_extend(uint32_t value, uint8_t index)
     762              : {
     763              :         __ASSERT_NO_MSG(index <= 31);
     764              : 
     765              :         uint8_t shift = 31 - index;
     766              : 
     767              :         return (int32_t)(value << shift) >> shift;
     768              : }
     769              : 
     770              : /**
     771              :  * @brief Sign extend a 64 bit value using the index bit as sign bit.
     772              :  *
     773              :  * @param value The value to sign expand.
     774              :  * @param index 0 based bit index to sign bit (0 to 63)
     775              :  */
     776            1 : static inline int64_t sign_extend_64(uint64_t value, uint8_t index)
     777              : {
     778              :         __ASSERT_NO_MSG(index <= 63);
     779              : 
     780              :         uint8_t shift = 63 - index;
     781              : 
     782              :         return (int64_t)(value << shift) >> shift;
     783              : }
     784              : 
     785              : #define __z_log2d(x) (32 - __builtin_clz(x) - 1)
     786              : #define __z_log2q(x) (64 - __builtin_clzll(x) - 1)
     787              : #define __z_log2(x) (sizeof(__typeof__(x)) > 4 ? __z_log2q(x) : __z_log2d(x))
     788              : 
     789              : /**
     790              :  * @brief Compute log2(x)
     791              :  *
     792              :  * @note This macro expands its argument multiple times (to permit use
     793              :  *       in constant expressions), which must not have side effects.
     794              :  *
     795              :  * @param x An unsigned integral value to compute logarithm of (positive only)
     796              :  *
     797              :  * @return log2(x) when 1 <= x <= max(x), -1 when x < 1
     798              :  */
     799            1 : #define LOG2(x) ((x) < 1 ? -1 : __z_log2(x))
     800              : 
     801              : /**
     802              :  * @brief Compute ceil(log2(x))
     803              :  *
     804              :  * @note This macro expands its argument multiple times (to permit use
     805              :  *       in constant expressions), which must not have side effects.
     806              :  *
     807              :  * @param x An unsigned integral value
     808              :  *
     809              :  * @return ceil(log2(x)) when 1 <= x <= max(type(x)), 0 when x < 1
     810              :  */
     811            1 : #define LOG2CEIL(x) ((x) <= 1 ?  0 : __z_log2((x)-1) + 1)
     812              : 
     813              : /**
     814              :  * @brief Compute next highest power of two
     815              :  *
     816              :  * Equivalent to 2^ceil(log2(x))
     817              :  *
     818              :  * @note This macro expands its argument multiple times (to permit use
     819              :  *       in constant expressions), which must not have side effects.
     820              :  *
     821              :  * @param x An unsigned integral value
     822              :  *
     823              :  * @return 2^ceil(log2(x)) or 0 if 2^ceil(log2(x)) would saturate 64-bits
     824              :  */
     825            1 : #define NHPOT(x) ((x) < 1 ? 1 : ((x) > (1ULL<<63) ? 0 : 1ULL << LOG2CEIL(x)))
     826              : 
     827              : /**
     828              :  * @brief Determine if a buffer exceeds highest address
     829              :  *
     830              :  * This macro determines if a buffer identified by a starting address @a addr
     831              :  * and length @a buflen spans a region of memory that goes beyond the highest
     832              :  * possible address (thereby resulting in a pointer overflow).
     833              :  *
     834              :  * @param addr Buffer starting address
     835              :  * @param buflen Length of the buffer
     836              :  *
     837              :  * @return true if pointer overflow detected, false otherwise
     838              :  */
     839              : #define Z_DETECT_POINTER_OVERFLOW(addr, buflen)  \
     840              :         (((buflen) != 0) &&                        \
     841              :         ((UINTPTR_MAX - (uintptr_t)(addr)) <= ((uintptr_t)((buflen) - 1))))
     842              : 
     843              : /**
     844              :  * @brief XOR n bytes
     845              :  *
     846              :  * @param dst  Destination of where to store result. Shall be @p len bytes.
     847              :  * @param src1 First source. Shall be @p len bytes.
     848              :  * @param src2 Second source. Shall be @p len bytes.
     849              :  * @param len  Number of bytes to XOR.
     850              :  */
     851            1 : static inline void mem_xor_n(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, size_t len)
     852              : {
     853              :         while (len--) {
     854              :                 *dst++ = *src1++ ^ *src2++;
     855              :         }
     856              : }
     857              : 
     858              : /**
     859              :  * @brief XOR 32 bits
     860              :  *
     861              :  * @param dst  Destination of where to store result. Shall be 32 bits.
     862              :  * @param src1 First source. Shall be 32 bits.
     863              :  * @param src2 Second source. Shall be 32 bits.
     864              :  */
     865            1 : static inline void mem_xor_32(uint8_t dst[4], const uint8_t src1[4], const uint8_t src2[4])
     866              : {
     867              :         mem_xor_n(dst, src1, src2, 4U);
     868              : }
     869              : 
     870              : /**
     871              :  * @brief XOR 128 bits
     872              :  *
     873              :  * @param dst  Destination of where to store result. Shall be 128 bits.
     874              :  * @param src1 First source. Shall be 128 bits.
     875              :  * @param src2 Second source. Shall be 128 bits.
     876              :  */
     877            1 : static inline void mem_xor_128(uint8_t dst[16], const uint8_t src1[16], const uint8_t src2[16])
     878              : {
     879              :         mem_xor_n(dst, src1, src2, 16);
     880              : }
     881              : 
     882              : /**
     883              :  * @brief Compare memory areas. The same way as `memcmp` it assume areas to be
     884              :  * the same length
     885              :  *
     886              :  * @param m1 First memory area to compare, cannot be NULL even if length is 0
     887              :  * @param m2 Second memory area to compare, cannot be NULL even if length is 0
     888              :  * @param n First n bytes of @p m1 and @p m2 to compares
     889              :  *
     890              :  * @returns true if the @p n first bytes of @p m1 and @p m2 are the same, else
     891              :  * false
     892              :  */
     893            1 : static inline bool util_memeq(const void *m1, const void *m2, size_t n)
     894              : {
     895              :         return memcmp(m1, m2, n) == 0;
     896              : }
     897              : 
     898              : /**
     899              :  * @brief Compare memory areas and their length
     900              :  *
     901              :  * If the length are 0, return true.
     902              :  *
     903              :  * @param m1 First memory area to compare, cannot be NULL even if length is 0
     904              :  * @param len1 Length of the first memory area to compare
     905              :  * @param m2 Second memory area to compare, cannot be NULL even if length is 0
     906              :  * @param len2 Length of the second memory area to compare
     907              :  *
     908              :  * @returns true if both the length of the memory areas and their content are
     909              :  * equal else false
     910              :  */
     911            1 : static inline bool util_eq(const void *m1, size_t len1, const void *m2, size_t len2)
     912              : {
     913              :         return len1 == len2 && (m1 == m2 || util_memeq(m1, m2, len1));
     914              : }
     915              : 
     916              : /**
     917              :  * @brief Returns the number of bits set in a value
     918              :  *
     919              :  * @param value The value to count number of bits set of
     920              :  * @param len The number of octets in @p value
     921              :  */
     922            1 : static inline size_t sys_count_bits(const void *value, size_t len)
     923              : {
     924              :         size_t cnt = 0U;
     925              :         size_t i = 0U;
     926              : 
     927              : #ifdef POPCOUNT
     928              :         for (; i < len / sizeof(unsigned int); i++) {
     929              :                 unsigned int val;
     930              :                 (void)memcpy(&val, (const uint8_t *)value + i * sizeof(unsigned int),
     931              :                              sizeof(unsigned int));
     932              : 
     933              :                 cnt += POPCOUNT(val);
     934              :         }
     935              :         i *= sizeof(unsigned int); /* convert to a uint8_t index for the remainder (if any) */
     936              : #endif
     937              : 
     938              :         for (; i < len; i++) {
     939              :                 uint8_t value_u8 = ((const uint8_t *)value)[i];
     940              : 
     941              :                 /* Implements Brian Kernighan’s Algorithm to count bits */
     942              :                 while (value_u8) {
     943              :                         value_u8 &= (value_u8 - 1);
     944              :                         cnt++;
     945              :                 }
     946              :         }
     947              : 
     948              :         return cnt;
     949              : }
     950              : 
     951              : #ifdef __cplusplus
     952              : }
     953              : #endif
     954              : 
     955              : /* This file must be included at the end of the !_ASMLANGUAGE guard.
     956              :  * It depends on macros defined in this file above which cannot be forward declared.
     957              :  */
     958              : #include <zephyr/sys/time_units.h>
     959              : 
     960              : #endif /* !_ASMLANGUAGE */
     961              : 
     962              : /** @brief Number of bytes in @p x kibibytes */
     963              : #ifdef _LINKER
     964              : /* This is used in linker scripts so need to avoid type casting there */
     965            1 : #define KB(x) ((x) << 10)
     966              : #else
     967              : #define KB(x) (((size_t)(x)) << 10)
     968              : #endif
     969              : /** @brief Number of bytes in @p x mebibytes */
     970            1 : #define MB(x) (KB(x) << 10)
     971              : /** @brief Number of bytes in @p x gibibytes */
     972            1 : #define GB(x) (MB(x) << 10)
     973              : 
     974              : /** @brief Number of Hz in @p x kHz */
     975            1 : #define KHZ(x) ((x) * 1000)
     976              : /** @brief Number of Hz in @p x MHz */
     977            1 : #define MHZ(x) (KHZ(x) * 1000)
     978              : 
     979              : /**
     980              :  * @brief For the POSIX architecture add a minimal delay in a busy wait loop.
     981              :  * For other architectures this is a no-op.
     982              :  *
     983              :  * In the POSIX ARCH, code takes zero simulated time to execute,
     984              :  * so busy wait loops become infinite loops, unless we
     985              :  * force the loop to take a bit of time.
     986              :  * Include this macro in all busy wait/spin loops
     987              :  * so they will also work when building for the POSIX architecture.
     988              :  *
     989              :  * @param t Time in microseconds we will busy wait
     990              :  */
     991              : #if defined(CONFIG_ARCH_POSIX)
     992              : #define Z_SPIN_DELAY(t) k_busy_wait(t)
     993              : #else
     994              : #define Z_SPIN_DELAY(t)
     995              : #endif
     996              : 
     997              : /**
     998              :  * @brief Wait for an expression to return true with a timeout
     999              :  *
    1000              :  * Spin on an expression with a timeout and optional delay between iterations
    1001              :  *
    1002              :  * Commonly needed when waiting on hardware to complete an asynchronous
    1003              :  * request to read/write/initialize/reset, but useful for any expression.
    1004              :  *
    1005              :  * @param expr Truth expression upon which to poll, e.g.: XYZREG & XYZREG_EN
    1006              :  * @param timeout Timeout to wait for in microseconds, e.g.: 1000 (1ms)
    1007              :  * @param delay_stmt Delay statement to perform each poll iteration
    1008              :  *                   e.g.: NULL, k_yield(), k_msleep(1) or k_busy_wait(1)
    1009              :  *
    1010              :  * @retval expr As a boolean return, if false then it has timed out.
    1011              :  */
    1012            1 : #define WAIT_FOR(expr, timeout, delay_stmt)                                                        \
    1013              :         ({                                                                                         \
    1014              :                 uint32_t _wf_cycle_count = k_us_to_cyc_ceil32(timeout);                            \
    1015              :                 uint32_t _wf_start = k_cycle_get_32();                                             \
    1016              :                 while (!(expr) && (_wf_cycle_count > (k_cycle_get_32() - _wf_start))) {            \
    1017              :                         delay_stmt;                                                                \
    1018              :                         Z_SPIN_DELAY(10);                                                          \
    1019              :                 }                                                                                  \
    1020              :                 (expr);                                                                            \
    1021              :         })
    1022              : 
    1023              : /**
    1024              :  * @}
    1025              :  */
    1026              : 
    1027              : #endif /* ZEPHYR_INCLUDE_SYS_UTIL_H_ */
        

Generated by: LCOV version 2.0-1