circbuf.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * (C) Copyright 2003
  4. * Gerry Hamel, geh@ti.com, Texas Instruments
  5. */
  6. #include <common.h>
  7. #include <log.h>
  8. #include <malloc.h>
  9. #include <circbuf.h>
  10. int buf_init (circbuf_t * buf, unsigned int size)
  11. {
  12. assert (buf != NULL);
  13. buf->size = 0;
  14. buf->totalsize = size;
  15. buf->data = (char *) malloc (sizeof (char) * size);
  16. assert (buf->data != NULL);
  17. buf->top = buf->data;
  18. buf->tail = buf->data;
  19. buf->end = &(buf->data[size]);
  20. return 1;
  21. }
  22. int buf_free (circbuf_t * buf)
  23. {
  24. assert (buf != NULL);
  25. assert (buf->data != NULL);
  26. free (buf->data);
  27. memset (buf, 0, sizeof (circbuf_t));
  28. return 1;
  29. }
  30. int buf_pop (circbuf_t * buf, char *dest, unsigned int len)
  31. {
  32. unsigned int i;
  33. char *p;
  34. assert (buf != NULL);
  35. assert (dest != NULL);
  36. p = buf->top;
  37. /* Cap to number of bytes in buffer */
  38. if (len > buf->size)
  39. len = buf->size;
  40. for (i = 0; i < len; i++) {
  41. dest[i] = *p++;
  42. /* Bounds check. */
  43. if (p == buf->end) {
  44. p = buf->data;
  45. }
  46. }
  47. /* Update 'top' pointer */
  48. buf->top = p;
  49. buf->size -= len;
  50. return len;
  51. }
  52. int buf_push (circbuf_t * buf, const char *src, unsigned int len)
  53. {
  54. /* NOTE: this function allows push to overwrite old data. */
  55. unsigned int i;
  56. char *p;
  57. assert (buf != NULL);
  58. assert (src != NULL);
  59. p = buf->tail;
  60. for (i = 0; i < len; i++) {
  61. *p++ = src[i];
  62. if (p == buf->end) {
  63. p = buf->data;
  64. }
  65. /* Make sure pushing too much data just replaces old data */
  66. if (buf->size < buf->totalsize) {
  67. buf->size++;
  68. } else {
  69. buf->top++;
  70. if (buf->top == buf->end) {
  71. buf->top = buf->data;
  72. }
  73. }
  74. }
  75. /* Update 'tail' pointer */
  76. buf->tail = p;
  77. return len;
  78. }