ringbuf.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * \file
  3. * Ring Buffer library
  4. */
  5. #include "mqtt/ringbuf.h"
  6. /**
  7. * \brief init a RINGBUF object
  8. * \param r pointer to a RINGBUF object
  9. * \param buf pointer to a byte array
  10. * \param size size of buf
  11. * \return 0 if successfull, otherwise failed
  12. */
  13. I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size)
  14. {
  15. if (r == NULL || buf == NULL || size < 2) return -1;
  16. r->p_o = r->p_r = r->p_w = buf;
  17. r->fill_cnt = 0;
  18. r->size = size;
  19. return 0;
  20. }
  21. /**
  22. * \brief put a character into ring buffer
  23. * \param r pointer to a ringbuf object
  24. * \param c character to be put
  25. * \return 0 if successfull, otherwise failed
  26. */
  27. I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c)
  28. {
  29. if (r->fill_cnt >= r->size)return -1; // ring buffer is full, this should be atomic operation
  30. r->fill_cnt++; // increase filled slots count, this should be atomic operation
  31. *r->p_w++ = c; // put character into buffer
  32. if (r->p_w >= r->p_o + r->size) // rollback if write pointer go pass
  33. r->p_w = r->p_o; // the physical boundary
  34. return 0;
  35. }
  36. /**
  37. * \brief get a character from ring buffer
  38. * \param r pointer to a ringbuf object
  39. * \param c read character
  40. * \return 0 if successfull, otherwise failed
  41. */
  42. I16 ICACHE_FLASH_ATTR RINGBUF_Get(RINGBUF *r, U8* c)
  43. {
  44. if (r->fill_cnt <= 0)return -1; // ring buffer is empty, this should be atomic operation
  45. r->fill_cnt--; // decrease filled slots count
  46. *c = *r->p_r++; // get the character out
  47. if (r->p_r >= r->p_o + r->size) // rollback if write pointer go pass
  48. r->p_r = r->p_o; // the physical boundary
  49. return 0;
  50. }