DataHelper.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "DataHelper.h"
  2. /**
  3. * 初始化一个先入先出缓冲
  4. *
  5. * @author lxz (041620 15:15:44)
  6. *
  7. * @param fifo 缓冲对象
  8. * @param buffer 数据缓冲
  9. * @param total 总数据大小
  10. */
  11. void dh_fifo_init(fifo_buffer_t *fifo, int total) {
  12. fifo->total = total;
  13. fifo->count = 0;
  14. fifo->head = 0;
  15. fifo->tail = 0;
  16. }
  17. /**
  18. * 缓冲保存一个数据
  19. *
  20. * @author lxz (041620 15:16:14)
  21. *
  22. * @param fifo 缓冲对象
  23. * @param dat 缓冲数据
  24. */
  25. int dh_fifo_push(fifo_buffer_t * fifo, unsigned char *dat ,unsigned int len) {
  26. if (fifo->count + 1 < fifo->total) {
  27. DH_ENTER_CRITCAL();
  28. // 分配内存并复制数据
  29. unsigned char *dataCopy = (unsigned char *)malloc(len);
  30. for (int i = 0; i < len; i++) {
  31. dataCopy[i] = dat[i];
  32. }
  33. fifo->buffer[fifo->head] = dataCopy;
  34. if (++fifo->head >= fifo->total) {
  35. fifo->head = 0;
  36. }
  37. fifo->count++;
  38. DH_EXIT_CRITCAL();
  39. return 1;
  40. }
  41. return 0;
  42. }
  43. /**
  44. *
  45. *
  46. * @author lxz (041620 15:16:43)
  47. *
  48. * @param fifo
  49. * @param dat
  50. *
  51. * @return int
  52. */
  53. int dh_fifo_pop(fifo_buffer_t *fifo, unsigned char *dat) {
  54. if (fifo->count > 0) {
  55. DH_ENTER_CRITCAL();
  56. memcpy(dat,fifo->buffer[fifo->tail],sizeof(fifo->buffer[fifo->tail]));
  57. free(fifo->buffer[fifo->tail]);
  58. if (++fifo->tail >= fifo->total) {
  59. fifo->tail = 0;
  60. }
  61. fifo->count--;
  62. DH_EXIT_CRITCAL();
  63. return (sizeof(fifo->buffer[fifo->tail]));
  64. }
  65. return 0;
  66. }