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