1 /*
2 * Copyright (C) 2018-2022 Intel Corporation.
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7 #ifndef UTIL_H
8 #define UTIL_H
9 #include <types.h>
10
11 #define offsetof(st, m) __builtin_offsetof(st, m)
12 #define va_start __builtin_va_start
13 #define va_end __builtin_va_end
14
15 /** Roundup (x/y) to ( x/y + (x%y) ? 1 : 0) **/
16 #define INT_DIV_ROUNDUP(x, y) ((((x)+(y))-1)/(y))
17
18 /** Roundup (x) to (y) aligned **/
19 #define roundup(x, y) (((x) + ((y) - 1UL)) & (~((y) - 1UL)))
20
21 #define min(x, y) (((x) < (y)) ? (x) : (y))
22
23 #define max(x, y) (((x) < (y)) ? (y) : (x))
24
25 /** return a value of v clamped to the range [l, h] */
26 #define clamp(v, l, h) (max(min((v), (h)), (l)))
27
28 /** Replaces 'x' by the string "x". */
29 #define STRINGIFY(x) #x
30
31 /* Macro used to check if a value is aligned to the required boundary.
32 * Returns TRUE if aligned; FALSE if not aligned
33 * NOTE: The required alignment must be a power of 2 (2, 4, 8, 16, 32, etc)
34 */
mem_aligned_check(uint64_t value,uint64_t req_align)35 static inline bool mem_aligned_check(uint64_t value, uint64_t req_align)
36 {
37 return ((value & (req_align - 1UL)) == 0UL);
38 }
39
40 /**
41 * @pre buf != NULL
42 */
calculate_sum8(const void * buf,uint32_t length)43 static inline uint8_t calculate_sum8(const void *buf, uint32_t length)
44 {
45 uint32_t i;
46 uint8_t sum = 0U;
47
48 for (i = 0U; i < length; i++) {
49 sum += *((const uint8_t *)buf + i);
50 }
51
52 return sum;
53 }
54
55 /**
56 * @pre buf != NULL
57 */
calculate_checksum8(const void * buf,uint32_t len)58 static inline uint8_t calculate_checksum8(const void *buf, uint32_t len)
59 {
60 return (uint8_t)(0x100U - calculate_sum8(buf, len));
61 }
62
63 /**
64 * @pre (uuid1 != NULL) && (uuid2 != NULL)
65 */
uuid_is_equal(const uint8_t * uuid1,const uint8_t * uuid2)66 static inline bool uuid_is_equal(const uint8_t *uuid1, const uint8_t *uuid2)
67 {
68 uint64_t uuid1_h = *(const uint64_t *)uuid1;
69 uint64_t uuid1_l = *(const uint64_t *)(uuid1 + 8);
70 uint64_t uuid2_h = *(const uint64_t *)uuid2;
71 uint64_t uuid2_l = *(const uint64_t *)(uuid2 + 8);
72
73 return ((uuid1_h == uuid2_h) && (uuid1_l == uuid2_l));
74 }
75
76 #endif /* UTIL_H */
77