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
8#include "util/memory.h"
9
10void RingFIFOInit(struct RingFIFO* buffer, size_t capacity, size_t maxalloc) {
11 buffer->data = anonymousMemoryMap(capacity);
12 buffer->capacity = capacity;
13 buffer->maxalloc = maxalloc;
14 RingFIFOClear(buffer);
15}
16
17void RingFIFODeinit(struct RingFIFO* buffer) {
18 mappedMemoryFree(buffer->data, buffer->capacity);
19 buffer->data = 0;
20}
21
22size_t RingFIFOCapacity(const struct RingFIFO* buffer) {
23 return buffer->capacity;
24}
25
26void RingFIFOClear(struct RingFIFO* buffer) {
27 buffer->readPtr = buffer->data;
28 buffer->writePtr = buffer->data;
29}
30
31size_t RingFIFOWrite(struct RingFIFO* buffer, const void* value, size_t length) {
32 void* data = buffer->writePtr;
33 void* end = buffer->readPtr;
34 size_t remaining;
35 if ((intptr_t) data - (intptr_t) buffer->data + buffer->maxalloc >= buffer->capacity) {
36 data = buffer->data;
37 }
38 if (data >= end) {
39 remaining = (intptr_t) buffer->data + buffer->capacity - (intptr_t) data;
40 } else {
41 remaining = (intptr_t) end - (intptr_t) data;
42 }
43 if (remaining <= length) {
44 return 0;
45 }
46 if (value) {
47 memcpy(data, value, length);
48 }
49 buffer->writePtr = (void*) ((intptr_t) data + length);
50 return length;
51}
52
53size_t RingFIFORead(struct RingFIFO* buffer, void* output, size_t length) {
54 void* data = buffer->readPtr;
55 void* end = buffer->writePtr;
56 size_t remaining;
57 if ((intptr_t) data - (intptr_t) buffer->data + buffer->maxalloc >= buffer->capacity) {
58 data = buffer->data;
59 }
60 if (data > end) {
61 remaining = (intptr_t) buffer->data + buffer->capacity - (intptr_t) data;
62 } else {
63 remaining = (intptr_t) end - (intptr_t) data;
64 }
65 if (remaining <= length) {
66 return 0;
67 }
68 if (output) {
69 memcpy(output, data, length);
70 }
71 buffer->readPtr = (void*) ((intptr_t) data + length);
72 return length;
73}