blob: 461c240f78828fc0f9821f841b1a2234f23cbf1f [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001// SPDX-License-Identifier: GPL-2.0+
wdenk232c1502004-03-12 00:14:09 +00002/*
3 * (C) Copyright 2003
4 * Gerry Hamel, geh@ti.com, Texas Instruments
wdenk232c1502004-03-12 00:14:09 +00005 */
6
Simon Glassf7ae49f2020-05-10 11:40:05 -06007#include <log.h>
wdenk232c1502004-03-12 00:14:09 +00008#include <malloc.h>
9
10#include <circbuf.h>
11
wdenk232c1502004-03-12 00:14:09 +000012int buf_init (circbuf_t * buf, unsigned int size)
13{
14 assert (buf != NULL);
15
16 buf->size = 0;
17 buf->totalsize = size;
18 buf->data = (char *) malloc (sizeof (char) * size);
19 assert (buf->data != NULL);
20
21 buf->top = buf->data;
22 buf->tail = buf->data;
23 buf->end = &(buf->data[size]);
24
25 return 1;
26}
27
28int buf_free (circbuf_t * buf)
29{
30 assert (buf != NULL);
31 assert (buf->data != NULL);
32
33 free (buf->data);
34 memset (buf, 0, sizeof (circbuf_t));
35
36 return 1;
37}
38
39int buf_pop (circbuf_t * buf, char *dest, unsigned int len)
40{
41 unsigned int i;
xypron.glpk@gmx.de05d887b2017-05-03 23:20:10 +020042 char *p;
wdenk232c1502004-03-12 00:14:09 +000043
44 assert (buf != NULL);
45 assert (dest != NULL);
46
xypron.glpk@gmx.de05d887b2017-05-03 23:20:10 +020047 p = buf->top;
48
wdenk232c1502004-03-12 00:14:09 +000049 /* Cap to number of bytes in buffer */
50 if (len > buf->size)
51 len = buf->size;
52
53 for (i = 0; i < len; i++) {
54 dest[i] = *p++;
55 /* Bounds check. */
56 if (p == buf->end) {
57 p = buf->data;
58 }
59 }
60
61 /* Update 'top' pointer */
62 buf->top = p;
63 buf->size -= len;
64
65 return len;
66}
67
68int buf_push (circbuf_t * buf, const char *src, unsigned int len)
69{
70 /* NOTE: this function allows push to overwrite old data. */
71 unsigned int i;
xypron.glpk@gmx.de05d887b2017-05-03 23:20:10 +020072 char *p;
wdenk232c1502004-03-12 00:14:09 +000073
74 assert (buf != NULL);
75 assert (src != NULL);
76
xypron.glpk@gmx.de05d887b2017-05-03 23:20:10 +020077 p = buf->tail;
78
wdenk232c1502004-03-12 00:14:09 +000079 for (i = 0; i < len; i++) {
80 *p++ = src[i];
81 if (p == buf->end) {
82 p = buf->data;
83 }
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;
91 }
92 }
93 }
94
95 /* Update 'tail' pointer */
96 buf->tail = p;
97
98 return len;
99}