about summary refs log tree commit diff stats
path: root/kernel.soso/fifobuffer.c
blob: 58fd145dfba2ece9d41748b2b622edbff38a0179 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "fifobuffer.h"
#include "alloc.h"

FifoBuffer* FifoBuffer_create(uint32 capacity) {
    FifoBuffer* fifo = (FifoBuffer*)kmalloc(sizeof(FifoBuffer));
    memset((uint8*)fifo, 0, sizeof(FifoBuffer));
    fifo->data = (uint8*)kmalloc(capacity);
    memset((uint8*)fifo->data, 0, capacity);
    fifo->capacity= capacity;

    return fifo;
}

void FifoBuffer_destroy(FifoBuffer* fifoBuffer) {
    kfree(fifoBuffer->data);
    kfree(fifoBuffer);
}

void FifoBuffer_clear(FifoBuffer* fifoBuffer) {
    fifoBuffer->usedBytes = 0;
    fifoBuffer->readIndex = 0;
    fifoBuffer->writeIndex = 0;
}

BOOL FifoBuffer_isEmpty(FifoBuffer* fifoBuffer) {
    if (0 == fifoBuffer->usedBytes) {
        return TRUE;
    }

    return FALSE;
}

uint32 FifoBuffer_getSize(FifoBuffer* fifoBuffer) {
    return fifoBuffer->usedBytes;
}

uint32 FifoBuffer_getCapacity(FifoBuffer* fifoBuffer) {
    return fifoBuffer->capacity;
}

uint32 FifoBuffer_getFree(FifoBuffer* fifoBuffer) {
    return fifoBuffer->capacity - fifoBuffer->usedBytes;
}

int32 FifoBuffer_enqueue(FifoBuffer* fifoBuffer, uint8* data, uint32 size) {
    if (size == 0) {
        return -1;
    }

    uint32 bytesAvailable = fifoBuffer->capacity - fifoBuffer->usedBytes;

    if (size > bytesAvailable) {
        return -1;
    }

    uint32 i = 0;
    while (fifoBuffer->usedBytes < fifoBuffer->capacity && i < size) {
        fifoBuffer->data[fifoBuffer->writeIndex] = data[i++];
        fifoBuffer->usedBytes++;
        fifoBuffer->writeIndex++;
        fifoBuffer->writeIndex %= fifoBuffer->capacity;
    }

    return size;
}

int32 FifoBuffer_dequeue(FifoBuffer* fifoBuffer, uint8* data, uint32 size) {
    if (size == 0) {
        return -1;
    }

    if (0 == fifoBuffer->usedBytes) {
        //Buffer is empty
        return 0;
    }

    uint32 i = 0;
    while (fifoBuffer->usedBytes > 0 && i < size) {
        data[i++] = fifoBuffer->data[fifoBuffer->readIndex];
        fifoBuffer->usedBytes--;
        fifoBuffer->readIndex++;
        fifoBuffer->readIndex %= fifoBuffer->capacity;
    }

    return i;
}