all repos — mgba @ 2c826e208c9e194d22c657e70d95dfc1008d18de

mGBA Game Boy Advance Emulator

src/util/circle-buffer.c (view raw)

 1#include "circle-buffer.h"
 2
 3#include <stddef.h>	
 4#include <stdlib.h>
 5
 6void CircleBufferInit(struct CircleBuffer* buffer, unsigned capacity) {
 7	buffer->data = malloc(capacity);
 8	buffer->capacity = capacity;
 9	buffer->size = 0;
10	buffer->readPtr = buffer->data;
11	buffer->writePtr = buffer->data;
12}
13
14void CircleBufferDeinit(struct CircleBuffer* buffer) {
15	free(buffer->data);
16	buffer->data = 0;
17}
18
19unsigned CircleBufferSize(const struct CircleBuffer* buffer) {
20	return buffer->size;
21}
22
23int CircleBufferWrite8(struct CircleBuffer* buffer, int8_t value) {
24	int8_t* data = buffer->writePtr;
25	if (buffer->size + sizeof(int8_t) > buffer->capacity) {
26		return 0;
27	}
28	*data = value;
29	++data;
30	ptrdiff_t size = (int8_t*) data - (int8_t*) buffer->data;
31	if (size < buffer->capacity) {
32		buffer->writePtr = data;
33	} else {
34		buffer->writePtr = buffer->data;
35	}
36	buffer->size += sizeof(int8_t);
37	return 1;
38}
39
40int CircleBufferWrite32(struct CircleBuffer* buffer, int32_t value) {
41	int32_t* data = buffer->writePtr;
42	if (buffer->size + sizeof(int32_t) > buffer->capacity) {
43		return 0;
44	}
45	*data = value;
46	++data;
47	ptrdiff_t size = (int8_t*) data - (int8_t*) buffer->data;
48	if (size < buffer->capacity) {
49		buffer->writePtr = data;
50	} else {
51		buffer->writePtr = buffer->data;
52	}
53	buffer->size += sizeof(int32_t);
54	return 1;
55}
56
57int CircleBufferRead8(struct CircleBuffer* buffer, int8_t* value) {
58	int8_t* data = buffer->readPtr;
59	if (buffer->size < sizeof(int8_t)) {
60		return 0;
61	}
62	*value = *data;
63	++data;
64	ptrdiff_t size = (int8_t*) data - (int8_t*) buffer->data;
65	if (size < buffer->capacity) {
66		buffer->readPtr = data;
67	} else {
68		buffer->readPtr = buffer->data;
69	}
70	buffer->size -= sizeof(int8_t);
71	return 1;
72}
73
74int CircleBufferRead32(struct CircleBuffer* buffer, int32_t* value) {
75	int32_t* data = buffer->readPtr;
76	if (buffer->size < sizeof(int32_t)) {
77		return 0;
78	}
79	*value = *data;
80	++data;
81	ptrdiff_t size = (int8_t*) data - (int8_t*) buffer->data;
82	if (size < buffer->capacity) {
83		buffer->readPtr = data;
84	} else {
85		buffer->readPtr = buffer->data;
86	}
87	buffer->size -= sizeof(int32_t);
88	return 1;
89}