serial_ring_buf.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* Serial ring buffer: 4096-byte circular buffer for COM1 receive.
  2. Single writer (IRQ), single reader (process) — no locks needed. */
  3. #include "serial_ring_buf.h"
  4. static volatile unsigned char ring_buf[SERIAL_RING_SIZE];
  5. static volatile unsigned int ring_head; /* write index, IRQ only */
  6. static volatile unsigned int ring_tail; /* read index, process only */
  7. void serial_ring_init(void)
  8. {
  9. ring_head = 0;
  10. ring_tail = 0;
  11. }
  12. void serial_ring_push(unsigned char byte)
  13. {
  14. unsigned int next = (ring_head + 1) % SERIAL_RING_SIZE;
  15. if (next != ring_tail) {
  16. ring_buf[ring_head] = byte;
  17. ring_head = next;
  18. }
  19. }
  20. int serial_ring_pop(unsigned char *byte)
  21. {
  22. if (ring_tail == ring_head)
  23. return 0;
  24. *byte = ring_buf[ring_tail];
  25. ring_tail = (ring_tail + 1) % SERIAL_RING_SIZE;
  26. return 1;
  27. }
  28. unsigned int serial_ring_count(void)
  29. {
  30. unsigned int h = ring_head;
  31. unsigned int t = ring_tail;
  32. if (h >= t)
  33. return h - t;
  34. return SERIAL_RING_SIZE - t + h;
  35. }
  36. /* Peek at byte `offset` from the front of the queue without consuming it.
  37. * Returns 1 and stores the byte, or 0 if `offset` is past the queued data. */
  38. int serial_ring_peek(unsigned int offset, unsigned char *byte)
  39. {
  40. unsigned int h = ring_head;
  41. unsigned int t = ring_tail;
  42. unsigned int count = (h >= t) ? (h - t) : (SERIAL_RING_SIZE - t + h);
  43. if (offset >= count)
  44. return 0;
  45. *byte = ring_buf[(t + offset) % SERIAL_RING_SIZE];
  46. return 1;
  47. }