• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2013 Red Hat, Inc.
4  */
5 
6 #ifndef _UTIL_H_
7 #define _UTIL_H_
8 
9 #include "config.h"
10 #include <stdbool.h>
11 #include <string.h>
12 
13 #define LONG_BITS (sizeof(long) * 8)
14 #define NLONGS(x) (((x) + LONG_BITS - 1) / LONG_BITS)
15 #define ARRAY_LENGTH(a) (sizeof(a) / (sizeof((a)[0])))
16 #define unlikely(x) (__builtin_expect(!!(x),0))
17 
18 #undef min
19 #undef max
20 #ifdef __GNUC__
21 #define min(a,b) \
22 		({ __typeof__ (a) _a = (a); \
23 	          __typeof__ (b) _b = (b); \
24 		_a > _b ? _b : _a; \
25 		})
26 #define max(a,b) \
27 		({ __typeof__ (a) _a = (a); \
28 	          __typeof__ (b) _b = (b); \
29 		_a > _b ? _a : _b; \
30 		})
31 #else
32 #define min(a,b) ((a) > (b) ? (b) : (a))
33 #define max(a,b) ((a) > (b) ? (a) : (b))
34 #endif
35 
36 static inline bool
startswith(const char * str,size_t len,const char * prefix,size_t plen)37 startswith(const char *str, size_t len, const char *prefix, size_t plen)
38 {
39 	return len >= plen && !strncmp(str, prefix, plen);
40 }
41 
42 static inline int
bit_is_set(const unsigned long * array,int bit)43 bit_is_set(const unsigned long *array, int bit)
44 {
45     return !!(array[bit / LONG_BITS] & (1LL << (bit % LONG_BITS)));
46 }
47 
48 static inline void
set_bit(unsigned long * array,int bit)49 set_bit(unsigned long *array, int bit)
50 {
51     array[bit / LONG_BITS] |= (1LL << (bit % LONG_BITS));
52 }
53 
54 static inline void
clear_bit(unsigned long * array,int bit)55 clear_bit(unsigned long *array, int bit)
56 {
57     array[bit / LONG_BITS] &= ~(1LL << (bit % LONG_BITS));
58 }
59 
60 static inline void
set_bit_state(unsigned long * array,int bit,int state)61 set_bit_state(unsigned long *array, int bit, int state)
62 {
63 	if (state)
64 		set_bit(array, bit);
65 	else
66 		clear_bit(array, bit);
67 }
68 
69 #endif
70