]> Git Repo - u-boot.git/blob - lib/circbuf.c
fwu: add dependency checks for selecting FWU metadata version
[u-boot.git] / lib / circbuf.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2003
4  * Gerry Hamel, [email protected], Texas Instruments
5  */
6
7 #include <log.h>
8 #include <malloc.h>
9
10 #include <circbuf.h>
11
12 int 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
28 int 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
39 int buf_pop (circbuf_t * buf, char *dest, unsigned int len)
40 {
41         unsigned int i;
42         char *p;
43
44         assert (buf != NULL);
45         assert (dest != NULL);
46
47         p = buf->top;
48
49         /* 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
68 int 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;
72         char *p;
73
74         assert (buf != NULL);
75         assert (src != NULL);
76
77         p = buf->tail;
78
79         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 }
This page took 0.031672 seconds and 4 git commands to generate.