util.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #ifndef UTIL_H_
  2. #define UTIL_H_
  3. #include <stdint.h>
  4. #include <avr/io.h>
  5. #include <avr/interrupt.h>
  6. #define likely(x) __builtin_expect(!!(x), 1)
  7. #define unlikely(x) __builtin_expect(!!(x), 0)
  8. #define min(a, b) ((a) < (b) ? (a) : (b))
  9. #define max(a, b) ((a) > (b) ? (a) : (b))
  10. #define abs(x) ({ \
  11. __typeof__(x) __x = (x); \
  12. (__x < 0) ? -__x : __x; \
  13. })
  14. #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
  15. /* Memory barrier.
  16. * The CPU doesn't have runtime reordering, so we just
  17. * need a compiler memory clobber. */
  18. #define mb() __asm__ __volatile__("" : : : "memory")
  19. /* Convert something indirectly to a string */
  20. #define __stringify(x) #x
  21. #define stringify(x) __stringify(x)
  22. typedef _Bool bool;
  23. #define true ((bool)(!!1))
  24. #define false ((bool)(!!0))
  25. static inline void irq_disable(void)
  26. {
  27. cli();
  28. mb();
  29. }
  30. static inline void irq_enable(void)
  31. {
  32. mb();
  33. sei();
  34. }
  35. static inline uint8_t irq_disable_save(void)
  36. {
  37. uint8_t sreg = SREG;
  38. cli();
  39. mb();
  40. return sreg;
  41. }
  42. static inline void irq_restore(uint8_t sreg_flags)
  43. {
  44. mb();
  45. SREG = sreg_flags;
  46. }
  47. #endif /* UTIL_H_ */