circbuf.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*
  2. * (C) Copyright 2003
  3. * Gerry Hamel, geh@ti.com, Texas Instruments
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. *
  19. */
  20. #include <common.h>
  21. #include <malloc.h>
  22. #include <circbuf.h>
  23. int buf_init (circbuf_t * buf, unsigned int size)
  24. {
  25. assert (buf != NULL);
  26. buf->size = 0;
  27. buf->totalsize = size;
  28. buf->data = (char *) malloc (sizeof (char) * size);
  29. assert (buf->data != NULL);
  30. buf->top = buf->data;
  31. buf->tail = buf->data;
  32. buf->end = &(buf->data[size]);
  33. return 1;
  34. }
  35. int buf_free (circbuf_t * buf)
  36. {
  37. assert (buf != NULL);
  38. assert (buf->data != NULL);
  39. free (buf->data);
  40. memset (buf, 0, sizeof (circbuf_t));
  41. return 1;
  42. }
  43. int buf_pop (circbuf_t * buf, char *dest, unsigned int len)
  44. {
  45. unsigned int i;
  46. char *p = buf->top;
  47. assert (buf != NULL);
  48. assert (dest != NULL);
  49. /* Cap to number of bytes in buffer */
  50. if (len > buf->size)
  51. len = buf->size;
  52. for (i = 0; i < len; i++) {
  53. dest[i] = *p++;
  54. /* Bounds check. */
  55. if (p == buf->end) {
  56. p = buf->data;
  57. }
  58. }
  59. /* Update 'top' pointer */
  60. buf->top = p;
  61. buf->size -= len;
  62. return len;
  63. }
  64. int buf_push (circbuf_t * buf, const char *src, unsigned int len)
  65. {
  66. /* NOTE: this function allows push to overwrite old data. */
  67. unsigned int i;
  68. char *p = buf->tail;
  69. assert (buf != NULL);
  70. assert (src != NULL);
  71. for (i = 0; i < len; i++) {
  72. *p++ = src[i];
  73. if (p == buf->end) {
  74. p = buf->data;
  75. }
  76. /* Make sure pushing too much data just replaces old data */
  77. if (buf->size < buf->totalsize) {
  78. buf->size++;
  79. } else {
  80. buf->top++;
  81. if (buf->top == buf->end) {
  82. buf->top = buf->data;
  83. }
  84. }
  85. }
  86. /* Update 'tail' pointer */
  87. buf->tail = p;
  88. return len;
  89. }