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.

44 lines
1.1 KiB

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