misc.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2023-02-25 GuEe-GUI the first version
  9. */
  10. #ifndef __MISC_H__
  11. #define __MISC_H__
  12. #include <rtdef.h>
  13. #ifdef ARCH_CPU_64BIT
  14. #define RT_BITS_PER_LONG 64
  15. #else
  16. #define RT_BITS_PER_LONG 32
  17. #endif
  18. #define RT_BITS_PER_LONG_LONG 64
  19. #define RT_DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
  20. #define RT_DIV_ROUND_CLOSEST(x, divisor) \
  21. ({ \
  22. typeof(x) __x = x; \
  23. typeof(divisor) __d = divisor; \
  24. (((typeof(x))-1) > 0 || \
  25. ((typeof(divisor))-1) > 0 || \
  26. (((__x) > 0) == ((__d) > 0))) ? \
  27. (((__x) + ((__d) / 2)) / (__d)) : \
  28. (((__x) - ((__d) / 2)) / (__d)); \
  29. })
  30. #define RT_BIT(n) (1UL << (n))
  31. #define RT_BIT_ULL(n) (1ULL << (n))
  32. #define RT_BIT_MASK(nr) (1UL << ((nr) % RT_BITS_PER_LONG))
  33. #define RT_BIT_WORD(nr) ((nr) / RT_BITS_PER_LONG)
  34. #define RT_BITS_PER_BYTE 8
  35. #define RT_BITS_PER_TYPE(type) (sizeof(type) * RT_BITS_PER_BYTE)
  36. #define RT_BITS_TO_BYTES(nr) RT_DIV_ROUND_UP(nr, RT_BITS_PER_TYPE(char))
  37. #define RT_BITS_TO_LONGS(nr) RT_DIV_ROUND_UP(nr, RT_BITS_PER_TYPE(long))
  38. #define RT_GENMASK(h, l) (((~0UL) << (l)) & (~0UL >> (RT_BITS_PER_LONG - 1 - (h))))
  39. #define RT_GENMASK_ULL(h, l) (((~0ULL) << (l)) & (~0ULL >> (RT_BITS_PER_LONG_LONG - 1 - (h))))
  40. #define RT_ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
  41. #define rt_min(x, y) \
  42. ({ \
  43. typeof(x) _x = (x); \
  44. typeof(y) _y = (y); \
  45. (void) (&_x == &_y); \
  46. _x < _y ? _x : _y; \
  47. })
  48. #define rt_max(x, y) \
  49. ({ \
  50. typeof(x) _x = (x); \
  51. typeof(y) _y = (y); \
  52. (void) (&_x == &_y); \
  53. _x > _y ? _x : _y; \
  54. })
  55. #define rt_min_t(type, x, y) \
  56. ({ \
  57. type _x = (x); \
  58. type _y = (y); \
  59. _x < _y ? _x: _y; \
  60. })
  61. #define rt_clamp(val, lo, hi) rt_min((typeof(val))rt_max(val, lo), hi)
  62. #define rt_do_div(n, base) \
  63. ({ \
  64. rt_uint32_t _base = (base), _rem; \
  65. _rem = ((rt_uint64_t)(n)) % _base; \
  66. (n) = ((rt_uint64_t)(n)) / _base; \
  67. if (_rem > _base / 2) \
  68. ++(n); \
  69. _rem; \
  70. })
  71. #endif /* __MISC_H__ */