aboutsummaryrefslogtreecommitdiff
path: root/buffers.h
blob: 497a21c61bdd65efa6fcb1594640237d76ee5748 (plain)
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
/* This defines common buffer code for whole library.
 * It is preprocessor generated code.
 * Preprocessor variables chose different implementations. But final
 * implementation is only few lines of code. This way it is included directly
 * to code.
 */
#include "tasks.h"

#ifndef _IOE_BUFFERS_H_
#define _IOE_BUFFERS_H_

// Define new buffer
#define IOEBUFFER(name, size) struct { \
        uint8_t rindex, windex; \
        uint8_t data[size]; \
    } name;

#define IOEBUFFER_INIT(name, size) { \
    name.windex = size - 1; \
    name.rindex = size - 1; \
    }

#define IOEBUFFER_MODE_BLOCK 0
#define IOEBUFFER_MODE_OVERWRITE 1
#define IOEBUFFER_MODE_DROP 2
// Add data to buffer. If buffer is full then behavior is defined by selected mode.
#define IOEBUFFER_PUT(name, size, data, mode) \
    if (mode == IOEBUFFER_MODE_BLOCK) { \
        if (name.windex == 0) { \
            while (name.rindex == size - 1); \
        } else { \
            while (name.rindex == name.windex - 1); \
        } \
    } \
    name.data[name.windex] = data; \
    if (mode != IOEBUFFER_MODE_DROP || \
            (name.windex == 0 && name.rindex == size - 1) || \
            (name.rindex + 1 == name.windex)) { \
        if (name.windex == 0) \
            name.windex = size - 1; \
        else \
            name.windex--; \
    } \
    if (mode == IOEBUFFER_MODE_OVERWRITE && name.windex == name.rindex) { \
        if (name.windex == size - 1) \
            name.windex = 0; \
        else \
            name.windex++; \
    } else;

// Get data from buffer and store it to variable
#define IOEBUFFER_GET(name, size, variable) \
    if (name.rindex != name.windex) { \
        variable = name.data[name.rindex]; \
        if (name.rindex == 0) \
            name.rindex = size - 1; \
        else \
            name.rindex--; \
    } else { \
        variable = 0; \
    }

// Set count of buffered data to variable
#define IOEBUFFER_CNT(name, size, variable) \
    if (name.windex < name.rindex) \
        variable = name.rindex - name.windex; \
    else if (name.windex > name.rindex) \
        variable = size - name.windex + name.rindex; \
    else \
        variable = 0;

#endif /* _IOE_BUFFERS_H_ */