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 
32 /** @brief Number of bits that make up a type */
33 #define NUM_BITS(t) (sizeof(t) * 8)
34 
35 #ifdef __cplusplus
36 extern "C" {
37 #endif
38 
39 /**
40  * @defgroup sys-util Utility Functions
41  * @since 2.4
42  * @version 0.1.0
43  * @ingroup utilities
44  * @{
45  */
46 
47 /** @brief Cast @p x, a pointer, to an unsigned integer. */
48 #define POINTER_TO_UINT(x) ((uintptr_t) (x))
49 /** @brief Cast @p x, an unsigned integer, to a <tt>void*</tt>. */
50 #define UINT_TO_POINTER(x) ((void *) (uintptr_t) (x))
51 /** @brief Cast @p x, a pointer, to a signed integer. */
52 #define POINTER_TO_INT(x)  ((intptr_t) (x))
53 /** @brief Cast @p x, a signed integer, to a <tt>void*</tt>. */
54 #define INT_TO_POINTER(x)  ((void *) (intptr_t) (x))
55 
56 #if !(defined(__CHAR_BIT__) && defined(__SIZEOF_LONG__) && defined(__SIZEOF_LONG_LONG__))
57 #	error Missing required predefined macros for BITS_PER_LONG calculation
58 #endif
59 
60 /** Number of bits in a long int. */
61 #define BITS_PER_LONG	(__CHAR_BIT__ * __SIZEOF_LONG__)
62 
63 /** Number of bits in a long long int. */
64 #define BITS_PER_LONG_LONG	(__CHAR_BIT__ * __SIZEOF_LONG_LONG__)
65 
66 /**
67  * @brief Create a contiguous bitmask starting at bit position @p l
68  *        and ending at position @p h.
69  */
70 #define GENMASK(h, l) \
71 	(((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
72 
73 /**
74  * @brief Create a contiguous 64-bit bitmask starting at bit position @p l
75  *        and ending at position @p h.
76  */
77 #define GENMASK64(h, l) \
78 	(((~0ULL) - (1ULL << (l)) + 1) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))
79 
80 /** @brief Extract the Least Significant Bit from @p value. */
81 #define LSB_GET(value) ((value) & -(value))
82 
83 /**
84  * @brief Extract a bitfield element from @p value corresponding to
85  *	  the field mask @p mask.
86  */
87 #define FIELD_GET(mask, value)  (((value) & (mask)) / LSB_GET(mask))
88 
89 /**
90  * @brief Prepare a bitfield element using @p value with @p mask representing
91  *	  its field position and width. The result should be combined
92  *	  with other fields using a logical OR.
93  */
94 #define FIELD_PREP(mask, value) (((value) * LSB_GET(mask)) & (mask))
95 
96 /** @brief 0 if @p cond is true-ish; causes a compile error otherwise. */
97 #define ZERO_OR_COMPILE_ERROR(cond) ((int) sizeof(char[1 - 2 * !(cond)]) - 1)
98 
99 #if defined(__cplusplus)
100 
101 /* The built-in function used below for type checking in C is not
102  * supported by GNU C++.
103  */
104 #define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
105 
106 #else /* __cplusplus */
107 
108 /**
109  * @brief Zero if @p array has an array type, a compile error otherwise
110  *
111  * This macro is available only from C, not C++.
112  */
113 #define IS_ARRAY(array) \
114 	ZERO_OR_COMPILE_ERROR( \
115 		!__builtin_types_compatible_p(__typeof__(array), \
116 					      __typeof__(&(array)[0])))
117 
118 /**
119  * @brief Number of elements in the given @p array
120  *
121  * In C++, due to language limitations, this will accept as @p array
122  * any type that implements <tt>operator[]</tt>. The results may not be
123  * particularly meaningful in this case.
124  *
125  * In C, passing a pointer as @p array causes a compile error.
126  */
127 #define ARRAY_SIZE(array) \
128 	((size_t) (IS_ARRAY(array) + (sizeof(array) / sizeof((array)[0]))))
129 
130 #endif /* __cplusplus */
131 
132 /**
133  * @brief Whether @p ptr is an element of @p array
134  *
135  * This macro can be seen as a slightly stricter version of @ref PART_OF_ARRAY
136  * in that it also ensures that @p ptr is aligned to an array-element boundary
137  * of @p array.
138  *
139  * In C, passing a pointer as @p array causes a compile error.
140  *
141  * @param array the array in question
142  * @param ptr the pointer to check
143  *
144  * @return 1 if @p ptr is part of @p array, 0 otherwise
145  */
146 #define IS_ARRAY_ELEMENT(array, ptr)                                                               \
147 	((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) &&                          \
148 	 POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]) &&                    \
149 	 (POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) % sizeof((array)[0]) == 0)
150 
151 /**
152  * @brief Index of @p ptr within @p array
153  *
154  * With `CONFIG_ASSERT=y`, this macro will trigger a runtime assertion
155  * when @p ptr does not fall into the range of @p array or when @p ptr
156  * is not aligned to an array-element boundary of @p array.
157  *
158  * In C, passing a pointer as @p array causes a compile error.
159  *
160  * @param array the array in question
161  * @param ptr pointer to an element of @p array
162  *
163  * @return the array index of @p ptr within @p array, on success
164  */
165 #define ARRAY_INDEX(array, ptr)                                                                    \
166 	({                                                                                         \
167 		__ASSERT_NO_MSG(IS_ARRAY_ELEMENT(array, ptr));                                     \
168 		(__typeof__((array)[0]) *)(ptr) - (array);                                         \
169 	})
170 
171 /**
172  * @brief Check if a pointer @p ptr lies within @p array.
173  *
174  * In C but not C++, this causes a compile error if @p array is not an array
175  * (e.g. if @p ptr and @p array are mixed up).
176  *
177  * @param array an array
178  * @param ptr a pointer
179  * @return 1 if @p ptr is part of @p array, 0 otherwise
180  */
181 #define PART_OF_ARRAY(array, ptr)                                                                  \
182 	((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) &&                                \
183 	 POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]))
184 
185 /**
186  * @brief Array-index of @p ptr within @p array, rounded down
187  *
188  * This macro behaves much like @ref ARRAY_INDEX with the notable
189  * difference that it accepts any @p ptr in the range of @p array rather than
190  * exclusively a @p ptr aligned to an array-element boundary of @p array.
191  *
192  * With `CONFIG_ASSERT=y`, this macro will trigger a runtime assertion
193  * when @p ptr does not fall into the range of @p array.
194  *
195  * In C, passing a pointer as @p array causes a compile error.
196  *
197  * @param array the array in question
198  * @param ptr pointer to an element of @p array
199  *
200  * @return the array index of @p ptr within @p array, on success
201  */
202 #define ARRAY_INDEX_FLOOR(array, ptr)                                                              \
203 	({                                                                                         \
204 		__ASSERT_NO_MSG(PART_OF_ARRAY(array, ptr));                                        \
205 		(POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) / sizeof((array)[0]);              \
206 	})
207 
208 /**
209  * @brief Iterate over members of an array using an index variable
210  *
211  * @param array the array in question
212  * @param idx name of array index variable
213  */
214 #define ARRAY_FOR_EACH(array, idx) for (size_t idx = 0; (idx) < ARRAY_SIZE(array); ++(idx))
215 
216 /**
217  * @brief Iterate over members of an array using a pointer
218  *
219  * @param array the array in question
220  * @param ptr pointer to an element of @p array
221  */
222 #define ARRAY_FOR_EACH_PTR(array, ptr)                                                             \
223 	for (__typeof__(*(array)) *ptr = (array); (size_t)((ptr) - (array)) < ARRAY_SIZE(array);   \
224 	     ++(ptr))
225 
226 /**
227  * @brief Validate if two entities have a compatible type
228  *
229  * @param a the first entity to be compared
230  * @param b the second entity to be compared
231  * @return 1 if the two elements are compatible, 0 if they are not
232  */
233 #define SAME_TYPE(a, b) __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
234 
235 /**
236  * @brief Validate CONTAINER_OF parameters, only applies to C mode.
237  */
238 #ifndef __cplusplus
239 #define CONTAINER_OF_VALIDATE(ptr, type, field)               \
240 	BUILD_ASSERT(SAME_TYPE(*(ptr), ((type *)0)->field) || \
241 		     SAME_TYPE(*(ptr), void),                 \
242 		     "pointer type mismatch in CONTAINER_OF");
243 #else
244 #define CONTAINER_OF_VALIDATE(ptr, type, field)
245 #endif
246 
247 /**
248  * @brief Get a pointer to a structure containing the element
249  *
250  * Example:
251  *
252  *	struct foo {
253  *		int bar;
254  *	};
255  *
256  *	struct foo my_foo;
257  *	int *ptr = &my_foo.bar;
258  *
259  *	struct foo *container = CONTAINER_OF(ptr, struct foo, bar);
260  *
261  * Above, @p container points at @p my_foo.
262  *
263  * @param ptr pointer to a structure element
264  * @param type name of the type that @p ptr is an element of
265  * @param field the name of the field within the struct @p ptr points to
266  * @return a pointer to the structure that contains @p ptr
267  */
268 #define CONTAINER_OF(ptr, type, field)                               \
269 	({                                                           \
270 		CONTAINER_OF_VALIDATE(ptr, type, field)              \
271 		((type *)(((char *)(ptr)) - offsetof(type, field))); \
272 	})
273 
274 /**
275  * @brief Report the size of a struct field in bytes.
276  *
277  * @param type The structure containing the field of interest.
278  * @param member The field to return the size of.
279  *
280  * @return The field size.
281  */
282 #define SIZEOF_FIELD(type, member) sizeof((((type *)0)->member))
283 
284 /**
285  * @brief Concatenate input arguments
286  *
287  * Concatenate provided tokens into a combined token during the preprocessor pass.
288  * This can be used to, for ex., build an identifier out of multiple parts,
289  * where one of those parts may be, for ex, a number, another macro, or a macro argument.
290  *
291  * @param ... Tokens to concatencate
292  *
293  * @return Concatenated token.
294  */
295 #define CONCAT(...) \
296 	UTIL_CAT(_CONCAT_, NUM_VA_ARGS_LESS_1(__VA_ARGS__))(__VA_ARGS__)
297 
298 /**
299  * @brief Check if @p ptr is aligned to @p align alignment
300  */
301 #define IS_ALIGNED(ptr, align) (((uintptr_t)(ptr)) % (align) == 0)
302 
303 /**
304  * @brief Value of @p x rounded up to the next multiple of @p align.
305  */
306 #define ROUND_UP(x, align)                                   \
307 	((((unsigned long)(x) + ((unsigned long)(align) - 1)) / \
308 	  (unsigned long)(align)) * (unsigned long)(align))
309 
310 /**
311  * @brief Value of @p x rounded down to the previous multiple of @p align.
312  */
313 #define ROUND_DOWN(x, align)                                 \
314 	(((unsigned long)(x) / (unsigned long)(align)) * (unsigned long)(align))
315 
316 /** @brief Value of @p x rounded up to the next word boundary. */
317 #define WB_UP(x) ROUND_UP(x, sizeof(void *))
318 
319 /** @brief Value of @p x rounded down to the previous word boundary. */
320 #define WB_DN(x) ROUND_DOWN(x, sizeof(void *))
321 
322 /**
323  * @brief Divide and round up.
324  *
325  * Example:
326  * @code{.c}
327  * DIV_ROUND_UP(1, 2); // 1
328  * DIV_ROUND_UP(3, 2); // 2
329  * @endcode
330  *
331  * @param n Numerator.
332  * @param d Denominator.
333  *
334  * @return The result of @p n / @p d, rounded up.
335  */
336 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
337 
338 /**
339  * @brief Divide and round to the nearest integer.
340  *
341  * Example:
342  * @code{.c}
343  * DIV_ROUND_CLOSEST(5, 2); // 3
344  * DIV_ROUND_CLOSEST(5, -2); // -3
345  * DIV_ROUND_CLOSEST(5, 3); // 2
346  * @endcode
347  *
348  * @param n Numerator.
349  * @param d Denominator.
350  *
351  * @return The result of @p n / @p d, rounded to the nearest integer.
352  */
353 #define DIV_ROUND_CLOSEST(n, d)	\
354 	((((n) < 0) ^ ((d) < 0)) ? ((n) - ((d) / 2)) / (d) : \
355 	((n) + ((d) / 2)) / (d))
356 
357 /**
358  * @brief Ceiling function applied to @p numerator / @p divider as a fraction.
359  * @deprecated Use DIV_ROUND_UP() instead.
360  */
361 #define ceiling_fraction(numerator, divider) __DEPRECATED_MACRO \
362 	DIV_ROUND_UP(numerator, divider)
363 
364 #ifndef MAX
365 /**
366  * @brief Obtain the maximum of two values.
367  *
368  * @note Arguments are evaluated twice. Use Z_MAX for a GCC-only, single
369  * evaluation version
370  *
371  * @param a First value.
372  * @param b Second value.
373  *
374  * @returns Maximum value of @p a and @p b.
375  */
376 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
377 #endif
378 
379 #ifndef MIN
380 /**
381  * @brief Obtain the minimum of two values.
382  *
383  * @note Arguments are evaluated twice. Use Z_MIN for a GCC-only, single
384  * evaluation version
385  *
386  * @param a First value.
387  * @param b Second value.
388  *
389  * @returns Minimum value of @p a and @p b.
390  */
391 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
392 #endif
393 
394 #ifndef CLAMP
395 /**
396  * @brief Clamp a value to a given range.
397  *
398  * @note Arguments are evaluated multiple times. Use Z_CLAMP for a GCC-only,
399  * single evaluation version.
400  *
401  * @param val Value to be clamped.
402  * @param low Lowest allowed value (inclusive).
403  * @param high Highest allowed value (inclusive).
404  *
405  * @returns Clamped value.
406  */
407 #define CLAMP(val, low, high) (((val) <= (low)) ? (low) : MIN(val, high))
408 #endif
409 
410 /**
411  * @brief Checks if a value is within range.
412  *
413  * @note @p val is evaluated twice.
414  *
415  * @param val Value to be checked.
416  * @param min Lower bound (inclusive).
417  * @param max Upper bound (inclusive).
418  *
419  * @retval true If value is within range
420  * @retval false If the value is not within range
421  */
422 #define IN_RANGE(val, min, max) ((val) >= (min) && (val) <= (max))
423 
424 /**
425  * @brief Is @p x a power of two?
426  * @param x value to check
427  * @return true if @p x is a power of two, false otherwise
428  */
is_power_of_two(unsigned int x)429 static inline bool is_power_of_two(unsigned int x)
430 {
431 	return IS_POWER_OF_TWO(x);
432 }
433 
434 /**
435  * @brief Is @p p equal to ``NULL``?
436  *
437  * Some macros may need to check their arguments against NULL to support
438  * multiple use-cases, but NULL checks can generate warnings if such a macro
439  * is used in contexts where that particular argument can never be NULL.
440  *
441  * The warnings can be triggered if:
442  * a) all macros are expanded (e.g. when using CONFIG_COMPILER_SAVE_TEMPS=y)
443  * or
444  * b) tracking of macro expansions are turned off (-ftrack-macro-expansion=0)
445  *
446  * The warnings can be circumvented by using this inline function for doing
447  * the NULL check within the macro. The compiler is still able to optimize the
448  * NULL check out at a later stage.
449  *
450  * @param p Pointer to check
451  * @return true if @p p is equal to ``NULL``, false otherwise
452  */
is_null_no_warn(void * p)453 static ALWAYS_INLINE bool is_null_no_warn(void *p)
454 {
455 	return p == NULL;
456 }
457 
458 /**
459  * @brief Arithmetic shift right
460  * @param value value to shift
461  * @param shift number of bits to shift
462  * @return @p value shifted right by @p shift; opened bit positions are
463  *         filled with the sign bit
464  */
arithmetic_shift_right(int64_t value,uint8_t shift)465 static inline int64_t arithmetic_shift_right(int64_t value, uint8_t shift)
466 {
467 	int64_t sign_ext;
468 
469 	if (shift == 0U) {
470 		return value;
471 	}
472 
473 	/* extract sign bit */
474 	sign_ext = (value >> 63) & 1;
475 
476 	/* make all bits of sign_ext be the same as the value's sign bit */
477 	sign_ext = -sign_ext;
478 
479 	/* shift value and fill opened bit positions with sign bit */
480 	return (value >> shift) | (sign_ext << (64 - shift));
481 }
482 
483 /**
484  * @brief byte by byte memcpy.
485  *
486  * Copy `size` bytes of `src` into `dest`. This is guaranteed to be done byte by byte.
487  *
488  * @param dst Pointer to the destination memory.
489  * @param src Pointer to the source of the data.
490  * @param size The number of bytes to copy.
491  */
bytecpy(void * dst,const void * src,size_t size)492 static inline void bytecpy(void *dst, const void *src, size_t size)
493 {
494 	size_t i;
495 
496 	for (i = 0; i < size; ++i) {
497 		((volatile uint8_t *)dst)[i] = ((volatile const uint8_t *)src)[i];
498 	}
499 }
500 
501 /**
502  * @brief byte by byte swap.
503  *
504  * Swap @a size bytes between memory regions @a a and @a b. This is
505  * guaranteed to be done byte by byte.
506  *
507  * @param a Pointer to the first memory region.
508  * @param b Pointer to the second memory region.
509  * @param size The number of bytes to swap.
510  */
byteswp(void * a,void * b,size_t size)511 static inline void byteswp(void *a, void *b, size_t size)
512 {
513 	uint8_t t;
514 	uint8_t *aa = (uint8_t *)a;
515 	uint8_t *bb = (uint8_t *)b;
516 
517 	for (; size > 0; --size) {
518 		t = *aa;
519 		*aa++ = *bb;
520 		*bb++ = t;
521 	}
522 }
523 
524 /**
525  * @brief      Convert a single character into a hexadecimal nibble.
526  *
527  * @param c     The character to convert
528  * @param x     The address of storage for the converted number.
529  *
530  *  @return Zero on success or (negative) error code otherwise.
531  */
532 int char2hex(char c, uint8_t *x);
533 
534 /**
535  * @brief      Convert a single hexadecimal nibble into a character.
536  *
537  * @param c     The number to convert
538  * @param x     The address of storage for the converted character.
539  *
540  *  @return Zero on success or (negative) error code otherwise.
541  */
542 int hex2char(uint8_t x, char *c);
543 
544 /**
545  * @brief      Convert a binary array into string representation.
546  *
547  * @param buf     The binary array to convert
548  * @param buflen  The length of the binary array to convert
549  * @param hex     Address of where to store the string representation.
550  * @param hexlen  Size of the storage area for string representation.
551  *
552  * @return     The length of the converted string, or 0 if an error occurred.
553  */
554 size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen);
555 
556 /**
557  * @brief      Convert a hexadecimal string into a binary array.
558  *
559  * @param hex     The hexadecimal string to convert
560  * @param hexlen  The length of the hexadecimal string to convert.
561  * @param buf     Address of where to store the binary data
562  * @param buflen  Size of the storage area for binary data
563  *
564  * @return     The length of the binary array, or 0 if an error occurred.
565  */
566 size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen);
567 
568 /**
569  * @brief Convert a binary coded decimal (BCD 8421) value to binary.
570  *
571  * @param bcd BCD 8421 value to convert.
572  *
573  * @return Binary representation of input value.
574  */
bcd2bin(uint8_t bcd)575 static inline uint8_t bcd2bin(uint8_t bcd)
576 {
577 	return ((10 * (bcd >> 4)) + (bcd & 0x0F));
578 }
579 
580 /**
581  * @brief Convert a binary value to binary coded decimal (BCD 8421).
582  *
583  * @param bin Binary value to convert.
584  *
585  * @return BCD 8421 representation of input value.
586  */
bin2bcd(uint8_t bin)587 static inline uint8_t bin2bcd(uint8_t bin)
588 {
589 	return (((bin / 10) << 4) | (bin % 10));
590 }
591 
592 /**
593  * @brief      Convert a uint8_t into a decimal string representation.
594  *
595  * Convert a uint8_t value into its ASCII decimal string representation.
596  * The string is terminated if there is enough space in buf.
597  *
598  * @param buf     Address of where to store the string representation.
599  * @param buflen  Size of the storage area for string representation.
600  * @param value   The value to convert to decimal string
601  *
602  * @return     The length of the converted string (excluding terminator if
603  *             any), or 0 if an error occurred.
604  */
605 uint8_t u8_to_dec(char *buf, uint8_t buflen, uint8_t value);
606 
607 /**
608  * @brief Sign extend an 8, 16 or 32 bit value using the index bit as sign bit.
609  *
610  * @param value The value to sign expand.
611  * @param index 0 based bit index to sign bit (0 to 31)
612  */
sign_extend(uint32_t value,uint8_t index)613 static inline int32_t sign_extend(uint32_t value, uint8_t index)
614 {
615 	__ASSERT_NO_MSG(index <= 31);
616 
617 	uint8_t shift = 31 - index;
618 
619 	return (int32_t)(value << shift) >> shift;
620 }
621 
622 /**
623  * @brief Sign extend a 64 bit value using the index bit as sign bit.
624  *
625  * @param value The value to sign expand.
626  * @param index 0 based bit index to sign bit (0 to 63)
627  */
sign_extend_64(uint64_t value,uint8_t index)628 static inline int64_t sign_extend_64(uint64_t value, uint8_t index)
629 {
630 	__ASSERT_NO_MSG(index <= 63);
631 
632 	uint8_t shift = 63 - index;
633 
634 	return (int64_t)(value << shift) >> shift;
635 }
636 
637 /**
638  * @brief Properly truncate a NULL-terminated UTF-8 string
639  *
640  * Take a NULL-terminated UTF-8 string and ensure that if the string has been
641  * truncated (by setting the NULL terminator) earlier by other means, that
642  * the string ends with a properly formatted UTF-8 character (1-4 bytes).
643  *
644  * @htmlonly
645  * Example:
646  *      char test_str[] = "€€€";
647  *      char trunc_utf8[8];
648  *
649  *      printf("Original : %s\n", test_str); // €€€
650  *      strncpy(trunc_utf8, test_str, sizeof(trunc_utf8));
651  *      trunc_utf8[sizeof(trunc_utf8) - 1] = '\0';
652  *      printf("Bad      : %s\n", trunc_utf8); // €€�
653  *      utf8_trunc(trunc_utf8);
654  *      printf("Truncated: %s\n", trunc_utf8); // €€
655  * @endhtmlonly
656  *
657  * @param utf8_str NULL-terminated string
658  *
659  * @return Pointer to the @p utf8_str
660  */
661 char *utf8_trunc(char *utf8_str);
662 
663 /**
664  * @brief Copies a UTF-8 encoded string from @p src to @p dst
665  *
666  * The resulting @p dst will always be NULL terminated if @p n is larger than 0,
667  * and the @p dst string will always be properly UTF-8 truncated.
668  *
669  * @param dst The destination of the UTF-8 string.
670  * @param src The source string
671  * @param n   The size of the @p dst buffer. Maximum number of characters copied
672  *            is @p n - 1. If 0 nothing will be done, and the @p dst will not be
673  *            NULL terminated.
674  *
675  * @return Pointer to the @p dst
676  */
677 char *utf8_lcpy(char *dst, const char *src, size_t n);
678 
679 #define __z_log2d(x) (32 - __builtin_clz(x) - 1)
680 #define __z_log2q(x) (64 - __builtin_clzll(x) - 1)
681 #define __z_log2(x) (sizeof(__typeof__(x)) > 4 ? __z_log2q(x) : __z_log2d(x))
682 
683 /**
684  * @brief Compute log2(x)
685  *
686  * @note This macro expands its argument multiple times (to permit use
687  *       in constant expressions), which must not have side effects.
688  *
689  * @param x An unsigned integral value to compute logarithm of (positive only)
690  *
691  * @return log2(x) when 1 <= x <= max(x), -1 when x < 1
692  */
693 #define LOG2(x) ((x) < 1 ? -1 : __z_log2(x))
694 
695 /**
696  * @brief Compute ceil(log2(x))
697  *
698  * @note This macro expands its argument multiple times (to permit use
699  *       in constant expressions), which must not have side effects.
700  *
701  * @param x An unsigned integral value
702  *
703  * @return ceil(log2(x)) when 1 <= x <= max(type(x)), 0 when x < 1
704  */
705 #define LOG2CEIL(x) ((x) < 1 ?  0 : __z_log2((x)-1) + 1)
706 
707 /**
708  * @brief Compute next highest power of two
709  *
710  * Equivalent to 2^ceil(log2(x))
711  *
712  * @note This macro expands its argument multiple times (to permit use
713  *       in constant expressions), which must not have side effects.
714  *
715  * @param x An unsigned integral value
716  *
717  * @return 2^ceil(log2(x)) or 0 if 2^ceil(log2(x)) would saturate 64-bits
718  */
719 #define NHPOT(x) ((x) < 1 ? 1 : ((x) > (1ULL<<63) ? 0 : 1ULL << LOG2CEIL(x)))
720 
721 /**
722  * @brief Determine if a buffer exceeds highest address
723  *
724  * This macro determines if a buffer identified by a starting address @a addr
725  * and length @a buflen spans a region of memory that goes beyond the highest
726  * possible address (thereby resulting in a pointer overflow).
727  *
728  * @param addr Buffer starting address
729  * @param buflen Length of the buffer
730  *
731  * @return true if pointer overflow detected, false otherwise
732  */
733 #define Z_DETECT_POINTER_OVERFLOW(addr, buflen)  \
734 	(((buflen) != 0) &&                        \
735 	((UINTPTR_MAX - (uintptr_t)(addr)) <= ((uintptr_t)((buflen) - 1))))
736 
737 /**
738  * @brief XOR n bytes
739  *
740  * @param dst  Destination of where to store result. Shall be @p len bytes.
741  * @param src1 First source. Shall be @p len bytes.
742  * @param src2 Second source. Shall be @p len bytes.
743  * @param len  Number of bytes to XOR.
744  */
mem_xor_n(uint8_t * dst,const uint8_t * src1,const uint8_t * src2,size_t len)745 static inline void mem_xor_n(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, size_t len)
746 {
747 	while (len--) {
748 		*dst++ = *src1++ ^ *src2++;
749 	}
750 }
751 
752 /**
753  * @brief XOR 32 bits
754  *
755  * @param dst  Destination of where to store result. Shall be 32 bits.
756  * @param src1 First source. Shall be 32 bits.
757  * @param src2 Second source. Shall be 32 bits.
758  */
mem_xor_32(uint8_t dst[4],const uint8_t src1[4],const uint8_t src2[4])759 static inline void mem_xor_32(uint8_t dst[4], const uint8_t src1[4], const uint8_t src2[4])
760 {
761 	mem_xor_n(dst, src1, src2, 4U);
762 }
763 
764 /**
765  * @brief XOR 128 bits
766  *
767  * @param dst  Destination of where to store result. Shall be 128 bits.
768  * @param src1 First source. Shall be 128 bits.
769  * @param src2 Second source. Shall be 128 bits.
770  */
mem_xor_128(uint8_t dst[16],const uint8_t src1[16],const uint8_t src2[16])771 static inline void mem_xor_128(uint8_t dst[16], const uint8_t src1[16], const uint8_t src2[16])
772 {
773 	mem_xor_n(dst, src1, src2, 16);
774 }
775 
776 #ifdef __cplusplus
777 }
778 #endif
779 
780 /* This file must be included at the end of the !_ASMLANGUAGE guard.
781  * It depends on macros defined in this file above which cannot be forward declared.
782  */
783 #include <zephyr/sys/time_units.h>
784 
785 #endif /* !_ASMLANGUAGE */
786 
787 /** @brief Number of bytes in @p x kibibytes */
788 #ifdef _LINKER
789 /* This is used in linker scripts so need to avoid type casting there */
790 #define KB(x) ((x) << 10)
791 #else
792 #define KB(x) (((size_t)(x)) << 10)
793 #endif
794 /** @brief Number of bytes in @p x mebibytes */
795 #define MB(x) (KB(x) << 10)
796 /** @brief Number of bytes in @p x gibibytes */
797 #define GB(x) (MB(x) << 10)
798 
799 /** @brief Number of Hz in @p x kHz */
800 #define KHZ(x) ((x) * 1000)
801 /** @brief Number of Hz in @p x MHz */
802 #define MHZ(x) (KHZ(x) * 1000)
803 
804 /**
805  * @brief For the POSIX architecture add a minimal delay in a busy wait loop.
806  * For other architectures this is a no-op.
807  *
808  * In the POSIX ARCH, code takes zero simulated time to execute,
809  * so busy wait loops become infinite loops, unless we
810  * force the loop to take a bit of time.
811  * Include this macro in all busy wait/spin loops
812  * so they will also work when building for the POSIX architecture.
813  *
814  * @param t Time in microseconds we will busy wait
815  */
816 #if defined(CONFIG_ARCH_POSIX)
817 #define Z_SPIN_DELAY(t) k_busy_wait(t)
818 #else
819 #define Z_SPIN_DELAY(t)
820 #endif
821 
822 /**
823  * @brief Wait for an expression to return true with a timeout
824  *
825  * Spin on an expression with a timeout and optional delay between iterations
826  *
827  * Commonly needed when waiting on hardware to complete an asynchronous
828  * request to read/write/initialize/reset, but useful for any expression.
829  *
830  * @param expr Truth expression upon which to poll, e.g.: XYZREG & XYZREG_EN
831  * @param timeout Timeout to wait for in microseconds, e.g.: 1000 (1ms)
832  * @param delay_stmt Delay statement to perform each poll iteration
833  *                   e.g.: NULL, k_yield(), k_msleep(1) or k_busy_wait(1)
834  *
835  * @retval expr As a boolean return, if false then it has timed out.
836  */
837 #define WAIT_FOR(expr, timeout, delay_stmt)                                                        \
838 	({                                                                                         \
839 		uint32_t _wf_cycle_count = k_us_to_cyc_ceil32(timeout);                            \
840 		uint32_t _wf_start = k_cycle_get_32();                                             \
841 		while (!(expr) && (_wf_cycle_count > (k_cycle_get_32() - _wf_start))) {            \
842 			delay_stmt;                                                                \
843 			Z_SPIN_DELAY(10);                                                          \
844 		}                                                                                  \
845 		(expr);                                                                            \
846 	})
847 
848 /**
849  * @}
850  */
851 
852 #endif /* ZEPHYR_INCLUDE_SYS_UTIL_H_ */
853