circbuf.c 1.6 KB

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