Debian Codegraph @

src/utils/misc.h

raw symbols SCIP
1 // SPDX-License-Identifier: MPL-2.0
2 // Copyright (c) 2018 Yuxuan Shui <[email protected]>
3
4 #pragma once
5 #include <assert.h>
6 #include <limits.h>
7 #include <stdbool.h>
8 #include <stddef.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13
14 #include <picom/types.h>
15 #include <test.h>
16
17 #include <time.h>
18
19 #include "compiler.h"
20 #include "log.h"
21
22 #define ARR_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
23
24 #ifdef __FAST_MATH__
25 #warning Use of -ffast-math can cause rendering error or artifacts, \
26 therefore it is not recommended.
27 #endif
28
29 #ifdef __clang__
30 __attribute__((optnone))
31 #else
32 __attribute__((optimize("-fno-fast-math")))
33 #endif
34 static inline bool
35 safe_isnan(double a) {
36 return __builtin_isnan(a);
37 }
38
39 #ifdef __clang__
40 __attribute__((optnone))
41 #else
42 __attribute__((optimize("-fno-fast-math")))
43 #endif
44 static inline bool
45 safe_isinf(double a) {
46 return __builtin_isinf(a);
47 }
48
49 /// Same as assert(false), but make sure we abort _even in release builds_.
50 /// Silence compiler warning caused by release builds making some code paths reachable.
51 #define BUG() \
52 do { \
53 assert(false); \
54 abort(); \
55 } while (0)
56 /// Abort the program is `expr` is true. This is similar to assert, but it is not disabled
57 /// in release builds.
58 #define BUG_ON(expr) \
59 do { \
60 bool __bug_on_tmp = (expr); \
61 assert(!__bug_on_tmp && "Original expr: " #expr); \
62 if (__bug_on_tmp) { \
63 fprintf(stderr, "BUG_ON: \"%s\"\n", #expr); \
64 abort(); \
65 } \
66 } while (0)
67 /// Abort the program if `expr` is NULL. This is NOT disabled in release builds.
68 #define BUG_ON_NULL(expr) BUG_ON((expr) == NULL);
69 #define CHECK_EXPR(...) ((void)0)
70 /// Same as assert, but evaluates the expression even in release builds
71 #define CHECK(expr) \
72 do { \
73 auto _ = (expr); \
74 /* make sure the original expression appears in the assertion message */ \
75 assert((CHECK_EXPR(expr), _)); \
76 (void)_; \
77 } while (0)
78
79 /// Asserts that var is within [lower, upper]. Silence compiler warning about expressions
80 /// being always true or false.
81 #define ASSERT_IN_RANGE(var, lower, upper) \
82 do { \
83 auto __assert_in_range_tmp attr_unused = (var); \
84 _Pragma("GCC diagnostic push"); \
85 _Pragma("GCC diagnostic ignored \"-Wtype-limits\""); \
86 assert(__assert_in_range_tmp >= (lower)); \
87 assert(__assert_in_range_tmp <= (upper)); \
88 _Pragma("GCC diagnostic pop"); \
89 } while (0)
90
91 /// Asserts that var >= lower. Silence compiler warning about expressions
92 /// being always true or false.
93 #define ASSERT_GEQ(var, lower) \
94 do { \
95 auto __tmp attr_unused = (var); \
96 _Pragma("GCC diagnostic push"); \
97 _Pragma("GCC diagnostic ignored \"-Wtype-limits\""); \
98 assert(__tmp >= (lower)); \
99 _Pragma("GCC diagnostic pop"); \
100 } while (0)
101
102 // Some macros for checked cast
103 // Note these macros are not complete, as in, they won't work for every integer types. But
104 // they are good enough for our use cases.
105
106 #define to_int_checked(val) \
107 ({ \
108 int64_t __to_tmp = (val); \
109 ASSERT_IN_RANGE(__to_tmp, INT_MIN, INT_MAX); \
110 (int)__to_tmp; \
111 })
112
113 #define to_char_checked(val) \
114 ({ \
115 int64_t __to_tmp = (val); \
116 ASSERT_IN_RANGE(__to_tmp, CHAR_MIN, CHAR_MAX); \
117 (char)__to_tmp; \
118 })
119
120 #define to_u16_checked(val) \
121 ({ \
122 auto __to_tmp = (val); \
123 ASSERT_IN_RANGE(__to_tmp, 0, UINT16_MAX); \
124 (uint16_t) __to_tmp; \
125 })
126
127 #define to_i16_checked(val) \
128 ({ \
129 int64_t __to_tmp = (int64_t)(val); \
130 ASSERT_IN_RANGE(__to_tmp, INT16_MIN, INT16_MAX); \
131 (int16_t) __to_tmp; \
132 })
133
134 #define to_u32_checked(val) \
135 ({ \
136 auto __to_tmp = (val); \
137 int64_t __to_u32_max attr_unused = UINT32_MAX; /* silence clang \
138 tautological \
139 comparison warning */ \
140 ASSERT_IN_RANGE(__to_tmp, 0, __to_u32_max); \
141 (uint32_t) __to_tmp; \
142 })
143
144 static inline uint16_t u64_to_u16_saturated(uint64_t val) {
145 if (val > UINT16_MAX) {
146 return UINT16_MAX;
147 }
148 return (uint16_t)val;
149 }
150 static inline uint16_t double_to_u16_saturated(double val) {
151 BUG_ON(safe_isnan(val));
152 if (val < 0) {
153 return 0;
154 }
155 if (val > UINT16_MAX) {
156 return UINT16_MAX;
157 }
158 return (uint16_t)val;
159 }
160 static inline uint16_t i64_to_u16_saturated(int64_t val) {
161 if (val < 0) {
162 return 0;
163 }
164 if (val > UINT16_MAX) {
165 return UINT16_MAX;
166 }
167 return (uint16_t)val;
168 }
169 static inline uint16_t int_to_u16_saturated(int val) {
170 return i64_to_u16_saturated(val);
171 }
172
173 #define to_u16_saturated(val) \
174 _Generic((val), \
175 double: double_to_u16_saturated, \
176 float: double_to_u16_saturated, \
177 uint64_t: u64_to_u16_saturated, \
178 int: int_to_u16_saturated, \
179 default: i64_to_u16_saturated)((val))
180
181 static inline int32_t double_to_i32_saturated(double val) {
182 BUG_ON(safe_isnan(val));
183 if (val < INT32_MIN) {
184 return INT32_MIN;
185 }
186 if (val > INT32_MAX) {
187 return INT32_MAX;
188 }
189 return (int32_t)val;
190 }
191 static inline int32_t u64_to_i32_saturated(uint64_t val) {
192 if (val > INT32_MAX) {
193 return INT32_MAX;
194 }
195 return (int32_t)val;
196 }
197 static inline int32_t i64_to_i32_saturated(int64_t val) {
198 if (val < INT32_MIN) {
199 return INT32_MIN;
200 }
201 if (val > INT32_MAX) {
202 return INT32_MAX;
203 }
204 return (int32_t)val;
205 }
206
207 #define to_i32_saturated(val) \
208 _Generic((val), \
209 double: double_to_i32_saturated, \
210 float: double_to_i32_saturated, \
211 uint64_t: u64_to_i32_saturated, \
212 default: i64_to_i32_saturated)((val))
213
214 /* Are two types/vars the same type (ignoring qualifiers)? */
215 #define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
216
217 /**
218 * container_of - cast a member of a structure out to the containing structure
219 * @ptr: the pointer to the member.
220 * @type: the type of the container struct this is embedded in.
221 * @member: the name of the member within the struct.
222 *
223 * WARNING: any const qualifier of @ptr is lost.
224 */
225 #define container_of(ptr, type, member) \
226 ({ \
227 void *__mptr = (void *)(ptr); \
228 static_assert(is_same_type(*(ptr), ((type *)0)->member) || \
229 is_same_type(*(ptr), void), \
230 "pointer type mismatch in container_of()"); \
231 ((type *)(__mptr - offsetof(type, member))); \
232 })
233
234 /**
235 * Normalize an int value to a specific range.
236 *
237 * @param i int value to normalize
238 * @param min minimal value
239 * @param max maximum value
240 * @return normalized value
241 */
242 static inline int attr_const attr_unused normalize_i_range(int i, int min, int max) {
243 if (i > max) {
244 return max;
245 }
246 if (i < min) {
247 return min;
248 }
249 return i;
250 }
251
252 /// Generic integer abs()
253 #define iabs(val) \
254 ({ \
255 __auto_type __tmp = (val); \
256 __tmp > 0 ? __tmp : -__tmp; \
257 })
258 #define min2(a, b) ((a) > (b) ? (b) : (a))
259 #define max2(a, b) ((a) > (b) ? (a) : (b))
260 #define min3(a, b, c) min2(a, min2(b, c))
261
262 /// clamp `val` into interval [min, max]
263 #define clamp(val, min, max) max2(min2(val, max), min)
264
265 /**
266 * Normalize a double value to a specific range.
267 *
268 * @param d double value to normalize
269 * @param min minimal value
270 * @param max maximum value
271 * @return normalized value
272 */
273 static inline double attr_const normalize_d_range(double d, double min, double max) {
274 if (d > max) {
275 return max;
276 }
277 if (d < min) {
278 return min;
279 }
280 return d;
281 }
282
283 /**
284 * Normalize a double value to 0.\ 0 - 1.\ 0.
285 *
286 * @param d double value to normalize
287 * @return normalized value
288 */
289 static inline double attr_const attr_unused normalize_d(double d) {
290 return normalize_d_range(d, 0.0, 1.0);
291 }
292
293 /**
294 * Convert a hex RGB string to RGB
295 */
296 static inline struct color hex_to_rgb(const char *hex) {
297 struct color rgb;
298 // Ignore the # in front of the string
299 const char *sane_hex = hex + 1;
300 int hex_color = (int)strtol(sane_hex, NULL, 16);
301 rgb.red = (float)(hex_color >> 16) / 256;
302 rgb.green = (float)((hex_color & 0x00ff00) >> 8) / 256;
303 rgb.blue = (float)(hex_color & 0x0000ff) / 256;
304
305 return rgb;
306 }
307
308 attr_noret void
309 report_allocation_failure(const char *func, const char *file, unsigned int line);
310
311 /**
312 * @brief Quit if the passed-in pointer is empty.
313 */
314 static inline void *
315 allocchk_(const char *func_name, const char *file, unsigned int line, void *ptr) {
316 if (unlikely(!ptr)) {
317 report_allocation_failure(func_name, file, line);
318 }
319 return ptr;
320 }
321
322 /// @brief Wrapper of allocchk_().
323 #define allocchk(ptr) allocchk_(__func__, __FILE__, __LINE__, ptr)
324
325 /// @brief Wrapper of malloc().
326 #define cmalloc(type) ((type *)allocchk(malloc(sizeof(type))))
327
328 /// @brief Wrapper of malloc() that takes a size
329 #define cvalloc(size) allocchk(malloc(size))
330
331 /// @brief Wrapper of calloc().
332 #define ccalloc(nmemb, type) \
333 ({ \
334 auto tmp = (nmemb); \
335 ASSERT_GEQ(tmp, 0); \
336 ((type *)allocchk(calloc((size_t)tmp, sizeof(type)))); \
337 })
338
339 /// @brief Wrapper of realloc().
340 #define crealloc(ptr, nmemb) \
341 ({ \
342 auto tmp = (nmemb); \
343 ASSERT_GEQ(tmp, 0); \
344 ((__typeof__(ptr))allocchk(realloc((ptr), (size_t)tmp * sizeof(*(ptr))))); \
345 })
346
347 static inline void free_charpp(char **str) {
348 if (str) {
349 free(*str);
350 *str = NULL;
351 }
352 }
353
354 /// An allocated char* that is automatically freed when it goes out of scope.
355 #define scoped_charp char *cleanup(free_charpp)
356
357 ///
358 /// Calculates next closest power of two of 32bit integer n
359 /// ref: https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
360 ///
361 int next_power_of_two(int n);
362
363 // Find the k-th smallest element in an array.
364 int quickselect(int *elems, int nelem, int k);
365
366 void set_rr_scheduling(void);
367
368 // Some versions of the Android libc do not have timespec_get(), use
369 // clock_gettime() instead.
370 #ifdef __ANDROID__
371
372 #ifndef TIME_UTC
373 #define TIME_UTC 1
374 #endif
375
376 static inline int timespec_get(struct timespec *ts, int base) {
377 assert(base == TIME_UTC);
378 return clock_gettime(CLOCK_REALTIME, ts);
379 }
380 #endif
381
382 static inline int long_cmp(const long a, const long b) {
383 return a < b ? -1 : a > b;
384 }
385
386 /// Compare 2 timespecs. Return 1 if `x` is greater, -1 if `y` is greater, 0 if
387 /// they are equal.
388 static inline int timespec_cmp(struct timespec x, struct timespec y) {
389 return long_cmp(x.tv_sec, y.tv_sec) ?: long_cmp(x.tv_nsec, y.tv_nsec);
390 }
391
392 // vim: set noet sw=8 ts=8 :