all repos — mgba @ c14da05d8dca225010677643c32fea5c0ac8517a

mGBA Game Boy Advance Emulator

src/util/ring-fifo.c (view raw)

 1/* Copyright (c) 2013-2014 Jeffrey Pfau
 2 *
 3 * This Source Code Form is subject to the terms of the Mozilla Public
 4 * License, v. 2.0. If a copy of the MPL was not distributed with this
 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 6#include "ring-fifo.h"
 7
 8void RingFIFOInit(struct RingFIFO* buffer, size_t capacity, size_t maxalloc) {
 9	buffer->data = anonymousMemoryMap(capacity);
10	buffer->capacity = capacity;
11	buffer->maxalloc = maxalloc;
12	RingFIFOClear(buffer);
13}
14
15void RingFIFODeinit(struct RingFIFO* buffer) {
16	memoryMapFree(buffer->data, buffer->capacity);
17	buffer->data = 0;
18}
19
20size_t RingFIFOCapacity(const struct RingFIFO* buffer) {
21	return buffer->capacity;
22}
23
24void RingFIFOClear(struct RingFIFO* buffer) {
25	buffer->readPtr = buffer->data;
26	buffer->writePtr = buffer->data;
27}
28
29size_t RingFIFOWrite(struct RingFIFO* buffer, const void* value, size_t length) {
30	void* data = buffer->writePtr;
31	void* end = buffer->readPtr;
32	size_t remaining;
33	if ((intptr_t) data - (intptr_t) buffer->data + buffer->maxalloc >= buffer->capacity) {
34		data = buffer->data;
35	}
36	if (data >= end) {
37		remaining = (intptr_t) buffer->data + buffer->capacity - (intptr_t) data;
38	} else {
39		remaining = (intptr_t) end - (intptr_t) data;
40	}
41	if (remaining <= length) {
42		return 0;
43	}
44	memcpy(data, value, length);
45	buffer->writePtr = (void*) ((intptr_t) data + length);
46	return length;
47}
48
49size_t RingFIFORead(struct RingFIFO* buffer, void* output, size_t length) {
50	void* data = buffer->readPtr;
51	void* end = buffer->writePtr;
52	size_t remaining;
53	if ((intptr_t) data - (intptr_t) buffer->data + buffer->maxalloc >= buffer->capacity) {
54		data = buffer->data;
55	}
56	if (data > end) {
57		remaining = (intptr_t) buffer->data + buffer->capacity - (intptr_t) data;
58	} else {
59		remaining = (intptr_t) end - (intptr_t) data;
60	}
61	if (remaining <= length) {
62		return 0;
63	}
64	memcpy(output, data, length);
65	buffer->readPtr = (void*) ((intptr_t) data + length);
66	return length;
67}