useful.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #ifndef GRPC_SUPPORT_USEFUL_H
  19. #define GRPC_SUPPORT_USEFUL_H
  20. /** useful macros that don't belong anywhere else */
  21. #define GPR_MIN(a, b) ((a) < (b) ? (a) : (b))
  22. #define GPR_MAX(a, b) ((a) > (b) ? (a) : (b))
  23. #define GPR_CLAMP(a, min, max) ((a) < (min) ? (min) : (a) > (max) ? (max) : (a))
  24. /** rotl, rotr assume x is unsigned */
  25. #define GPR_ROTL(x, n) (((x) << (n)) | ((x) >> (sizeof(x) * 8 - (n))))
  26. #define GPR_ROTR(x, n) (((x) >> (n)) | ((x) << (sizeof(x) * 8 - (n))))
  27. #define GPR_ARRAY_SIZE(array) (sizeof(array) / sizeof(*(array)))
  28. #define GPR_SWAP(type, a, b) \
  29. do { \
  30. type x = a; \
  31. a = b; \
  32. b = x; \
  33. } while (0)
  34. /** Set the \a n-th bit of \a i (a mutable pointer). */
  35. #define GPR_BITSET(i, n) ((*(i)) |= (1u << (n)))
  36. /** Clear the \a n-th bit of \a i (a mutable pointer). */
  37. #define GPR_BITCLEAR(i, n) ((*(i)) &= ~(1u << (n)))
  38. /** Get the \a n-th bit of \a i */
  39. #define GPR_BITGET(i, n) (((i) & (1u << (n))) != 0)
  40. #define GPR_INTERNAL_HEXDIGIT_BITCOUNT(x) \
  41. ((x) - (((x) >> 1) & 0x77777777) - (((x) >> 2) & 0x33333333) - \
  42. (((x) >> 3) & 0x11111111))
  43. /** Returns number of bits set in bitset \a i */
  44. #define GPR_BITCOUNT(i) \
  45. (((GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) + \
  46. (GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) >> 4)) & \
  47. 0x0f0f0f0f) % \
  48. 255)
  49. #define GPR_ICMP(a, b) ((a) < (b) ? -1 : ((a) > (b) ? 1 : 0))
  50. #define GPR_HASH_POINTER(x, range) \
  51. ((((size_t)x) >> 4) ^ (((size_t)x) >> 9) ^ (((size_t)x) >> 14)) % (range)
  52. #endif /* GRPC_SUPPORT_USEFUL_H */