util.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #ifndef MY_UTIL_H_
  2. #define MY_UTIL_H_
  3. #include <stdint.h>
  4. #include <avr/interrupt.h>
  5. #define likely(x) __builtin_expect(!!(x), 1)
  6. #define unlikely(x) __builtin_expect(!!(x), 0)
  7. #undef offsetof
  8. #define offsetof(type, member) ((size_t)&((type *)0)->member)
  9. #define min(a, b) ((a) < (b) ? (a) : (b))
  10. #define max(a, b) ((a) > (b) ? (a) : (b))
  11. #define abs(x) ((x) >= 0 ? (x) : -(x))
  12. #define lo8(x) ((uint8_t)(x))
  13. #define hi8(x) ((uint8_t)((x) >> 8))
  14. #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
  15. #define BUILD_BUG_ON(x) ((void)sizeof(char[1 - 2 * !!(x)]))
  16. /* Progmem pointer annotation. */
  17. #define PROGPTR /* progmem pointer */
  18. /* Memory barrier.
  19. * The CPU doesn't have runtime reordering, so we just
  20. * need a compiler memory clobber. */
  21. #define mb() __asm__ __volatile__("" : : : "memory")
  22. /* Convert something indirectly to a string */
  23. #define __stringify(x) #x
  24. #define stringify(x) __stringify(x)
  25. /* Delay one CPU cycle */
  26. #undef nop
  27. #define nop() do { __asm__ __volatile__("nop\n"); } while (0)
  28. /* Code flow attributes */
  29. #define noreturn __attribute__((__noreturn__))
  30. #define _mainfunc __attribute__((__OS_main__))
  31. #if defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
  32. # define unreachable() __builtin_unreachable()
  33. #else
  34. # define unreachable() while (1)
  35. #endif
  36. /* Forced no-inline */
  37. #define noinline __attribute__((__noinline__))
  38. typedef _Bool bool;
  39. static inline void irq_disable(void)
  40. {
  41. cli();
  42. mb();
  43. }
  44. static inline void irq_enable(void)
  45. {
  46. mb();
  47. sei();
  48. }
  49. static inline uint8_t irq_disable_save(void)
  50. {
  51. uint8_t sreg = SREG;
  52. cli();
  53. mb();
  54. return sreg;
  55. }
  56. static inline void irq_restore(uint8_t sreg_flags)
  57. {
  58. mb();
  59. SREG = sreg_flags;
  60. }
  61. #define __irqs_disabled(sreg) (!((sreg) & (1 << SREG_I)))
  62. #define irqs_disabled() __irqs_disabled(SREG)
  63. #endif /* MY_UTIL_H_ */