ring_buffer.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #pragma once
  2. /*--------------------------------------------------------------------
  3. * Ring buffer to store scan codes from keyboard
  4. *------------------------------------------------------------------*/
  5. #ifndef RBUF_SIZE
  6. # define RBUF_SIZE 32
  7. #endif
  8. #include <util/atomic.h>
  9. #include <stdint.h>
  10. #include <stdbool.h>
  11. static uint8_t rbuf[RBUF_SIZE];
  12. static uint8_t rbuf_head = 0;
  13. static uint8_t rbuf_tail = 0;
  14. static inline bool rbuf_enqueue(uint8_t data) {
  15. bool ret = false;
  16. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  17. uint8_t next = (rbuf_head + 1) % RBUF_SIZE;
  18. if (next != rbuf_tail) {
  19. rbuf[rbuf_head] = data;
  20. rbuf_head = next;
  21. ret = true;
  22. }
  23. }
  24. return ret;
  25. }
  26. static inline uint8_t rbuf_dequeue(void) {
  27. uint8_t val = 0;
  28. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  29. if (rbuf_head != rbuf_tail) {
  30. val = rbuf[rbuf_tail];
  31. rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE;
  32. }
  33. }
  34. return val;
  35. }
  36. static inline bool rbuf_has_data(void) {
  37. bool has_data;
  38. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { has_data = (rbuf_head != rbuf_tail); }
  39. return has_data;
  40. }
  41. static inline void rbuf_clear(void) {
  42. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { rbuf_head = rbuf_tail = 0; }
  43. }