common_defines.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #pragma once
  2. #include <stdbool.h>
  3. #include <cmsis_os2.h>
  4. #ifndef MAX
  5. #define MAX(a, b) \
  6. ({ \
  7. __typeof__(a) _a = (a); \
  8. __typeof__(b) _b = (b); \
  9. _a > _b ? _a : _b; \
  10. })
  11. #endif
  12. #ifndef MIN
  13. #define MIN(a, b) \
  14. ({ \
  15. __typeof__(a) _a = (a); \
  16. __typeof__(b) _b = (b); \
  17. _a < _b ? _a : _b; \
  18. })
  19. #endif
  20. #ifndef ROUND_UP_TO
  21. #define ROUND_UP_TO(a, b) \
  22. ({ \
  23. __typeof__(a) _a = (a); \
  24. __typeof__(b) _b = (b); \
  25. _a / _b + !!(_a % _b); \
  26. })
  27. #endif
  28. #ifndef CLAMP
  29. #define CLAMP(x, upper, lower) (MIN(upper, MAX(x, lower)))
  30. #endif
  31. // need some common semantics for those two
  32. #ifndef SIZEOF_ARRAY
  33. #define SIZEOF_ARRAY(arr) (sizeof(arr) / sizeof(arr[0]))
  34. #endif
  35. #ifndef COUNT_OF
  36. #define COUNT_OF(x) (sizeof(x) / sizeof(x[0]))
  37. #endif
  38. #ifndef FURI_SWAP
  39. #define FURI_SWAP(x, y) \
  40. do { \
  41. typeof(x) SWAP = x; \
  42. x = y; \
  43. y = SWAP; \
  44. } while(0)
  45. #endif
  46. #ifndef PLACE_IN_SECTION
  47. #define PLACE_IN_SECTION(x) __attribute__((section(x)))
  48. #endif
  49. #ifndef ALIGN
  50. #define ALIGN(n) __attribute__((aligned(n)))
  51. #endif
  52. #ifndef STRINGIFY
  53. #define STRINGIFY(x) #x
  54. #endif
  55. #ifndef TOSTRING
  56. #define TOSTRING(x) STRINGIFY(x)
  57. #endif
  58. #ifndef REVERSE_BYTES_U32
  59. #define REVERSE_BYTES_U32(x) \
  60. ((((x)&0x000000FF) << 24) | (((x)&0x0000FF00) << 8) | (((x)&0x00FF0000) >> 8) | \
  61. (((x)&0xFF000000) >> 24))
  62. #endif
  63. #ifndef FURI_BIT
  64. #define FURI_BIT(x, n) ((x) >> (n)&1)
  65. #endif
  66. #ifndef FURI_IS_IRQ_MASKED
  67. #define FURI_IS_IRQ_MASKED() (__get_PRIMASK() != 0U)
  68. #endif
  69. #ifndef FURI_IS_IRQ_MODE
  70. #define FURI_IS_IRQ_MODE() (__get_IPSR() != 0U)
  71. #endif
  72. #ifndef FURI_IS_ISR
  73. #define FURI_IS_ISR() \
  74. (FURI_IS_IRQ_MODE() || (FURI_IS_IRQ_MASKED() && (osKernelGetState() == osKernelRunning)))
  75. #endif
  76. #ifndef FURI_CRITICAL_ENTER
  77. #define FURI_CRITICAL_ENTER() \
  78. uint32_t __isrm = 0; \
  79. bool __from_isr = FURI_IS_ISR(); \
  80. if(__from_isr) { \
  81. __isrm = taskENTER_CRITICAL_FROM_ISR(); \
  82. } else { \
  83. taskENTER_CRITICAL(); \
  84. }
  85. #endif
  86. #ifndef FURI_CRITICAL_EXIT
  87. #define FURI_CRITICAL_EXIT() \
  88. if(__from_isr) { \
  89. taskEXIT_CRITICAL_FROM_ISR(__isrm); \
  90. } else { \
  91. taskEXIT_CRITICAL(); \
  92. }
  93. #endif