2 * Generic FIFO component, implemented as a circular buffer.
4 * Copyright (c) 2012 Peter A. G. Crosthwaite
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.
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/>.
15 #include "qemu-common.h"
16 #include "qemu/fifo8.h"
18 void fifo8_create(Fifo8
*fifo
, uint32_t capacity
)
20 fifo
->data
= g_new(uint8_t, capacity
);
21 fifo
->capacity
= capacity
;
26 void fifo8_destroy(Fifo8
*fifo
)
31 void fifo8_push(Fifo8
*fifo
, uint8_t data
)
33 if (fifo
->num
== fifo
->capacity
) {
36 fifo
->data
[(fifo
->head
+ fifo
->num
) % fifo
->capacity
] = data
;
40 void fifo8_push_all(Fifo8
*fifo
, const uint8_t *data
, uint32_t num
)
42 uint32_t start
, avail
;
44 if (fifo
->num
+ num
> fifo
->capacity
) {
48 start
= (fifo
->head
+ fifo
->num
) % fifo
->capacity
;
50 if (start
+ num
<= fifo
->capacity
) {
51 memcpy(&fifo
->data
[start
], data
, num
);
53 avail
= fifo
->capacity
- start
;
54 memcpy(&fifo
->data
[start
], data
, avail
);
55 memcpy(&fifo
->data
[0], &data
[avail
], num
- avail
);
61 uint8_t fifo8_pop(Fifo8
*fifo
)
68 ret
= fifo
->data
[fifo
->head
++];
69 fifo
->head
%= fifo
->capacity
;
74 const uint8_t *fifo8_pop_buf(Fifo8
*fifo
, uint32_t max
, uint32_t *num
)
78 if (max
== 0 || max
> fifo
->num
) {
81 *num
= MIN(fifo
->capacity
- fifo
->head
, max
);
82 ret
= &fifo
->data
[fifo
->head
];
84 fifo
->head
%= fifo
->capacity
;
89 void fifo8_reset(Fifo8
*fifo
)
95 bool fifo8_is_empty(Fifo8
*fifo
)
97 return (fifo
->num
== 0);
100 bool fifo8_is_full(Fifo8
*fifo
)
102 return (fifo
->num
== fifo
->capacity
);
105 uint32_t fifo8_num_free(Fifo8
*fifo
)
107 return fifo
->capacity
- fifo
->num
;
110 uint32_t fifo8_num_used(Fifo8
*fifo
)
115 const VMStateDescription vmstate_fifo8
= {
118 .minimum_version_id
= 1,
119 .fields
= (VMStateField
[]) {
120 VMSTATE_VBUFFER_UINT32(data
, Fifo8
, 1, NULL
, 0, capacity
),
121 VMSTATE_UINT32(head
, Fifo8
),
122 VMSTATE_UINT32(num
, Fifo8
),
123 VMSTATE_END_OF_LIST()