all repos — mgba @ 09b4a4a29a6393d2c5e2671810d8b046d46fdf13

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->readPtr = buffer->data;
10	buffer->writePtr = (int8_t*) buffer->data + capacity;
11}
12
13void CircleBufferDeinit(struct CircleBuffer* buffer) {
14	free(buffer->data);
15	buffer->data = 0;
16}
17
18unsigned CircleBufferSize(const struct CircleBuffer* buffer) {
19	ptrdiff_t size = (int8_t*) buffer->readPtr - (int8_t*) buffer->writePtr;
20	if (size < 0) {
21		return buffer->capacity - size;
22	}
23	return size;
24}
25
26int CircleBufferWrite32(struct CircleBuffer* buffer, int32_t value) {
27	uint32_t* data = buffer->writePtr;
28	if ((int8_t*) buffer->writePtr + 1 == buffer->readPtr) {
29		return 0;
30	}
31	if ((int8_t*) buffer->writePtr == (int8_t*) buffer->data + buffer->capacity - 1 && buffer->readPtr == buffer->data) {
32		return 0;
33	}
34	*data = value;
35	++data;
36	ptrdiff_t size = (int8_t*) data - (int8_t*) buffer->data;
37	if (size < buffer->capacity) {
38		buffer->writePtr = data;
39	} else {
40		buffer->writePtr = buffer->data;
41	}
42	return 1;
43}
44
45int CircleBufferRead32(struct CircleBuffer* buffer, int32_t* value) {
46	uint32_t* data = buffer->readPtr;
47	if (buffer->readPtr == buffer->writePtr) {
48		return 0;
49	}
50	*value = *data;
51	++data;
52	ptrdiff_t size = (int8_t*) data - (int8_t*) buffer->data;
53	if (size < buffer->capacity) {
54		buffer->readPtr = data;
55	} else {
56		buffer->readPtr = buffer->data;
57	}
58	return 1;
59}