circbuf.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * (C) Copyright 2003
  3. * Gerry Hamel, geh@ti.com, Texas Instruments
  4. *
  5. * SPDX-License-Identifier: GPL-2.0+
  6. */
  7. #include <common.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 = buf->top;
  34. assert (buf != NULL);
  35. assert (dest != NULL);
  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 = buf->tail;
  56. assert (buf != NULL);
  57. assert (src != NULL);
  58. for (i = 0; i < len; i++) {
  59. *p++ = src[i];
  60. if (p == buf->end) {
  61. p = buf->data;
  62. }
  63. /* Make sure pushing too much data just replaces old data */
  64. if (buf->size < buf->totalsize) {
  65. buf->size++;
  66. } else {
  67. buf->top++;
  68. if (buf->top == buf->end) {
  69. buf->top = buf->data;
  70. }
  71. }
  72. }
  73. /* Update 'tail' pointer */
  74. buf->tail = p;
  75. return len;
  76. }