Merge patch series "led: add function naming option from linux"
[u-boot.git] / lib / circbuf.c
blob461c240f78828fc0f9821f841b1a2234f23cbf1f
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * (C) Copyright 2003
4 * Gerry Hamel, geh@ti.com, Texas Instruments
5 */
7 #include <log.h>
8 #include <malloc.h>
10 #include <circbuf.h>
12 int buf_init (circbuf_t * buf, unsigned int size)
14 assert (buf != NULL);
16 buf->size = 0;
17 buf->totalsize = size;
18 buf->data = (char *) malloc (sizeof (char) * size);
19 assert (buf->data != NULL);
21 buf->top = buf->data;
22 buf->tail = buf->data;
23 buf->end = &(buf->data[size]);
25 return 1;
28 int buf_free (circbuf_t * buf)
30 assert (buf != NULL);
31 assert (buf->data != NULL);
33 free (buf->data);
34 memset (buf, 0, sizeof (circbuf_t));
36 return 1;
39 int buf_pop (circbuf_t * buf, char *dest, unsigned int len)
41 unsigned int i;
42 char *p;
44 assert (buf != NULL);
45 assert (dest != NULL);
47 p = buf->top;
49 /* Cap to number of bytes in buffer */
50 if (len > buf->size)
51 len = buf->size;
53 for (i = 0; i < len; i++) {
54 dest[i] = *p++;
55 /* Bounds check. */
56 if (p == buf->end) {
57 p = buf->data;
61 /* Update 'top' pointer */
62 buf->top = p;
63 buf->size -= len;
65 return len;
68 int buf_push (circbuf_t * buf, const char *src, unsigned int len)
70 /* NOTE: this function allows push to overwrite old data. */
71 unsigned int i;
72 char *p;
74 assert (buf != NULL);
75 assert (src != NULL);
77 p = buf->tail;
79 for (i = 0; i < len; i++) {
80 *p++ = src[i];
81 if (p == buf->end) {
82 p = buf->data;
84 /* Make sure pushing too much data just replaces old data */
85 if (buf->size < buf->totalsize) {
86 buf->size++;
87 } else {
88 buf->top++;
89 if (buf->top == buf->end) {
90 buf->top = buf->data;
95 /* Update 'tail' pointer */
96 buf->tail = p;
98 return len;