xref: /openbmc/u-boot/lib/circbuf.c (revision 15855700)
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 
21 #include <common.h>
22 #include <malloc.h>
23 
24 #include <circbuf.h>
25 
26 
27 int buf_init (circbuf_t * buf, unsigned int size)
28 {
29 	assert (buf != NULL);
30 
31 	buf->size = 0;
32 	buf->totalsize = size;
33 	buf->data = (char *) malloc (sizeof (char) * size);
34 	assert (buf->data != NULL);
35 
36 	buf->top = buf->data;
37 	buf->tail = buf->data;
38 	buf->end = &(buf->data[size]);
39 
40 	return 1;
41 }
42 
43 int buf_free (circbuf_t * buf)
44 {
45 	assert (buf != NULL);
46 	assert (buf->data != NULL);
47 
48 	free (buf->data);
49 	memset (buf, 0, sizeof (circbuf_t));
50 
51 	return 1;
52 }
53 
54 int buf_pop (circbuf_t * buf, char *dest, unsigned int len)
55 {
56 	unsigned int i;
57 	char *p = buf->top;
58 
59 	assert (buf != NULL);
60 	assert (dest != NULL);
61 
62 	/* Cap to number of bytes in buffer */
63 	if (len > buf->size)
64 		len = buf->size;
65 
66 	for (i = 0; i < len; i++) {
67 		dest[i] = *p++;
68 		/* Bounds check. */
69 		if (p == buf->end) {
70 			p = buf->data;
71 		}
72 	}
73 
74 	/* Update 'top' pointer */
75 	buf->top = p;
76 	buf->size -= len;
77 
78 	return len;
79 }
80 
81 int buf_push (circbuf_t * buf, const char *src, unsigned int len)
82 {
83 	/* NOTE:  this function allows push to overwrite old data. */
84 	unsigned int i;
85 	char *p = buf->tail;
86 
87 	assert (buf != NULL);
88 	assert (src != NULL);
89 
90 	for (i = 0; i < len; i++) {
91 		*p++ = src[i];
92 		if (p == buf->end) {
93 			p = buf->data;
94 		}
95 		/* Make sure pushing too much data just replaces old data */
96 		if (buf->size < buf->totalsize) {
97 			buf->size++;
98 		} else {
99 			buf->top++;
100 			if (buf->top == buf->end) {
101 				buf->top = buf->data;
102 			}
103 		}
104 	}
105 
106 	/* Update 'tail' pointer */
107 	buf->tail = p;
108 
109 	return len;
110 }
111