You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.3 KiB

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