blob: 9848da3b7b6182df3957a8ac4c9dbfe8271d693f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
/*
* (C) Copyright 2003
* Gerry Hamel, geh@ti.com, Texas Instruments
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <malloc.h>
#include <circbuf.h>
int buf_init (circbuf_t * buf, unsigned int size)
{
assert (buf != NULL);
buf->size = 0;
buf->totalsize = size;
buf->data = (char *) malloc (sizeof (char) * size);
assert (buf->data != NULL);
buf->top = buf->data;
buf->tail = buf->data;
buf->end = &(buf->data[size]);
return 1;
}
int buf_free (circbuf_t * buf)
{
assert (buf != NULL);
assert (buf->data != NULL);
free (buf->data);
memset (buf, 0, sizeof (circbuf_t));
return 1;
}
int buf_pop (circbuf_t * buf, char *dest, unsigned int len)
{
unsigned int i;
char *p = buf->top;
assert (buf != NULL);
assert (dest != NULL);
/* Cap to number of bytes in buffer */
if (len > buf->size)
len = buf->size;
for (i = 0; i < len; i++) {
dest[i] = *p++;
/* Bounds check. */
if (p == buf->end) {
p = buf->data;
}
}
/* Update 'top' pointer */
buf->top = p;
buf->size -= len;
return len;
}
int buf_push (circbuf_t * buf, const char *src, unsigned int len)
{
/* NOTE: this function allows push to overwrite old data. */
unsigned int i;
char *p = buf->tail;
assert (buf != NULL);
assert (src != NULL);
for (i = 0; i < len; i++) {
*p++ = src[i];
if (p == buf->end) {
p = buf->data;
}
/* Make sure pushing too much data just replaces old data */
if (buf->size < buf->totalsize) {
buf->size++;
} else {
buf->top++;
if (buf->top == buf->end) {
buf->top = buf->data;
}
}
}
/* Update 'tail' pointer */
buf->tail = p;
return len;
}
|