fifo.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. * fifo.c
  3. *
  4. * Created on: Jan 17, 2022
  5. * Author: radioman
  6. */
  7. #include "fifo.h"
  8. #include <stdlib.h>
  9. #include <string.h>
  10. void fifo_init(FIFO_HandleTypeDef *fifo, uint8_t *buffer, uint32_t size)
  11. {
  12. fifo->head = fifo->tail = 0;
  13. fifo->state = FIFO_EMPTY;
  14. fifo->size = size;
  15. fifo->data = buffer;
  16. }
  17. FIFO_StateTypeDef fifo_state(FIFO_HandleTypeDef *fifo)
  18. {
  19. return fifo->state;
  20. }
  21. int fifo_read(FIFO_HandleTypeDef *fifo, uint8_t *buf, uint32_t len)
  22. {
  23. if(fifo->state != FIFO_EMPTY)
  24. {
  25. if(fifo->tail >= fifo->head)
  26. {
  27. uint32_t cap_avail = fifo->size - fifo->tail + fifo->head;
  28. if((fifo->size - fifo->tail) >= len)
  29. {
  30. memcpy(buf, &(fifo->data[fifo->tail]), len);
  31. fifo->tail = (fifo->tail + len) % fifo->size;
  32. }
  33. else
  34. {
  35. if(len > cap_avail)
  36. len = cap_avail;
  37. uint32_t blk1_sz = fifo->size - fifo->tail;
  38. memcpy(buf, &(fifo->data[fifo->tail]), blk1_sz);
  39. fifo->tail = 0;
  40. memcpy(&buf[blk1_sz], &(fifo->data[fifo->tail]), (len - blk1_sz));
  41. fifo->tail = (len - blk1_sz) % fifo->size;
  42. }
  43. }
  44. else
  45. {
  46. if(len > (fifo->head - fifo->tail))
  47. len = fifo->head - fifo->tail;
  48. memcpy(buf, &(fifo->data[fifo->tail]), len);
  49. fifo->tail = (fifo->tail + len) % fifo->size;
  50. }
  51. if(fifo->tail == fifo->head)
  52. fifo->state = FIFO_EMPTY;
  53. else
  54. fifo->state = FIFO_READY;
  55. return (len);
  56. }
  57. else
  58. {
  59. return (-1);
  60. }
  61. }
  62. int fifo_write(FIFO_HandleTypeDef *fifo, uint8_t *data, uint32_t len)
  63. {
  64. if(fifo->state != FIFO_FULL)
  65. {
  66. if(fifo->head >= fifo->tail)
  67. {
  68. uint32_t cap_avail = fifo->size - fifo->head + fifo->tail;
  69. if((fifo->size - fifo->head) >= len)
  70. {
  71. memcpy(&(fifo->data[fifo->head]), data, len);
  72. fifo->head = (fifo->head + len) % fifo->size;
  73. }
  74. else
  75. {
  76. if(len > cap_avail)
  77. len = cap_avail;
  78. uint32_t blk1_sz = fifo->size - fifo->head;
  79. memcpy(&(fifo->data[fifo->head]), data, blk1_sz);
  80. fifo->head = 0;
  81. memcpy(&(fifo->data[fifo->head]), &data[blk1_sz], (len - blk1_sz));
  82. fifo->head = (len - blk1_sz) % fifo->size;
  83. }
  84. }
  85. else
  86. {
  87. if(len > (fifo->tail - fifo->head))
  88. len = fifo->tail - fifo->head;
  89. memcpy(&(fifo->data[fifo->head]), data, len);
  90. fifo->head = (fifo->head + len) % fifo->size;
  91. }
  92. if(fifo->head == fifo->tail)
  93. fifo->state = FIFO_FULL;
  94. else
  95. fifo->state = FIFO_READY;
  96. return (len);
  97. }
  98. else
  99. {
  100. return (-1);
  101. }
  102. }