xref: /openbmc/qemu/util/fifo8.c (revision 1559e0d4)
1 /*
2  * Generic FIFO component, implemented as a circular buffer.
3  *
4  * Copyright (c) 2012 Peter A. G. Crosthwaite
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  *
11  * You should have received a copy of the GNU General Public License along
12  * with this program; if not, see <http://www.gnu.org/licenses/>.
13  */
14 
15 #include "qemu-common.h"
16 #include "qemu/fifo8.h"
17 
18 void fifo8_create(Fifo8 *fifo, uint32_t capacity)
19 {
20     fifo->data = g_new(uint8_t, capacity);
21     fifo->capacity = capacity;
22     fifo->head = 0;
23     fifo->num = 0;
24 }
25 
26 void fifo8_destroy(Fifo8 *fifo)
27 {
28     g_free(fifo->data);
29 }
30 
31 void fifo8_push(Fifo8 *fifo, uint8_t data)
32 {
33     if (fifo->num == fifo->capacity) {
34         abort();
35     }
36     fifo->data[(fifo->head + fifo->num) % fifo->capacity] = data;
37     fifo->num++;
38 }
39 
40 uint8_t fifo8_pop(Fifo8 *fifo)
41 {
42     uint8_t ret;
43 
44     if (fifo->num == 0) {
45         abort();
46     }
47     ret = fifo->data[fifo->head++];
48     fifo->head %= fifo->capacity;
49     fifo->num--;
50     return ret;
51 }
52 
53 void fifo8_reset(Fifo8 *fifo)
54 {
55     fifo->num = 0;
56 }
57 
58 bool fifo8_is_empty(Fifo8 *fifo)
59 {
60     return (fifo->num == 0);
61 }
62 
63 bool fifo8_is_full(Fifo8 *fifo)
64 {
65     return (fifo->num == fifo->capacity);
66 }
67 
68 const VMStateDescription vmstate_fifo8 = {
69     .name = "Fifo8",
70     .version_id = 1,
71     .minimum_version_id = 1,
72     .minimum_version_id_old = 1,
73     .fields      = (VMStateField[]) {
74         VMSTATE_VBUFFER_UINT32(data, Fifo8, 1, NULL, 0, capacity),
75         VMSTATE_UINT32(head, Fifo8),
76         VMSTATE_UINT32(num, Fifo8),
77         VMSTATE_END_OF_LIST()
78     }
79 };
80