• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #ifndef GRPC_CORE_LIB_GPR_USEFUL_H
20 #define GRPC_CORE_LIB_GPR_USEFUL_H
21 
22 /** useful macros that don't belong anywhere else */
23 
24 #define GPR_MIN(a, b) ((a) < (b) ? (a) : (b))
25 #define GPR_MAX(a, b) ((a) > (b) ? (a) : (b))
26 #define GPR_CLAMP(a, min, max) ((a) < (min) ? (min) : (a) > (max) ? (max) : (a))
27 /** rotl, rotr assume x is unsigned */
28 #define GPR_ROTL(x, n) (((x) << (n)) | ((x) >> (sizeof(x) * 8 - (n))))
29 #define GPR_ROTR(x, n) (((x) >> (n)) | ((x) << (sizeof(x) * 8 - (n))))
30 
31 #define GPR_ARRAY_SIZE(array) (sizeof(array) / sizeof(*(array)))
32 
33 #define GPR_SWAP(type, a, b) \
34   do {                       \
35     type x = a;              \
36     a = b;                   \
37     b = x;                   \
38   } while (0)
39 
40 /** Set the \a n-th bit of \a i (a mutable pointer). */
41 #define GPR_BITSET(i, n) ((*(i)) |= (1u << (n)))
42 
43 /** Clear the \a n-th bit of \a i (a mutable pointer). */
44 #define GPR_BITCLEAR(i, n) ((*(i)) &= ~(1u << (n)))
45 
46 /** Get the \a n-th bit of \a i */
47 #define GPR_BITGET(i, n) (((i) & (1u << (n))) != 0)
48 
49 #define GPR_INTERNAL_HEXDIGIT_BITCOUNT(x)                        \
50   ((x) - (((x) >> 1) & 0x77777777) - (((x) >> 2) & 0x33333333) - \
51    (((x) >> 3) & 0x11111111))
52 
53 /** Returns number of bits set in bitset \a i */
54 #define GPR_BITCOUNT(i)                          \
55   (((GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) +         \
56      (GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) >> 4)) & \
57     0x0f0f0f0f) %                                \
58    255)
59 
60 #define GPR_ICMP(a, b) ((a) < (b) ? -1 : ((a) > (b) ? 1 : 0))
61 
62 #define GPR_HASH_POINTER(x, range) \
63   ((((size_t)x) >> 4) ^ (((size_t)x) >> 9) ^ (((size_t)x) >> 14)) % (range)
64 
65 #endif /* GRPC_CORE_LIB_GPR_USEFUL_H */
66