aboutsummaryrefslogtreecommitdiff
path: root/circular_buffer.h
blob: a12bbbc4c34243bd1c6d52edf9dd441e24b4cc1e (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
73
74
75
76
77
78
79
80
81
82
/*
 * ------------------------------------------------------------
 * "THE BEERWARE LICENSE" (Revision 42):
 * diegohamilton26@gmail.com wrote this code. As long as you retain this 
 * notice, you can do whatever you want with this stuff. If we
 * meet someday, and you think this stuff is worth it, you can
 * buy me a beer in return,
 * Diego Hamilton.
 * ------------------------------------------------------------
 */

#ifndef _CIRCULAR_BUFFER_H
#define _CIRCULAR_BUFFER_H

#include <stddef.h>

/*
*   BUF must be a pointer of any buffer with type 'NAME' defined.
*   ELEM must be a element (NOT A POINTER) of type T defined.
*/

#define circular_buffer_struct(T, SIZE)    \
    struct {    \
        size_t occup;   \
        size_t size;    \
        size_t head, tail;  \
        T data[SIZE];    \
    }

#define cb_init(BUF, SIZE)  \
    do {    \
        (BUF).size = SIZE;   \
        (BUF).occup = 0;   \
        (BUF).head = 0;      \
        (BUF).tail = 0;      \
    } while(0)

#define cb_size(BUF) ((BUF).size)
#define cb_full(BUF) ((BUF).occup == (BUF).size)
#define cb_empty(BUF) ((BUF).occup == 0)
#define cb_occupation(BUF) ((BUF).occup)
#define cb_reset(BUF)   \
    do {    \
        (BUF).head = 0;  \
        (BUF).tail = 0;  \
        (BUF).occup = 0;  \
    } while(0)

/* TODO: replace occup by calculations w/ head and tail? */
#define cb_push(BUF, ELEM)  \
    do {    \
        ((BUF).data)[(BUF).tail] = (ELEM);   \
        if ((BUF).tail == cb_size(BUF) - 1) {  \
            (BUF).tail = 0;    \
        } else {    \
            (BUF).tail = ((BUF).tail + 1);    \
        }   \
        if (cb_full((BUF))) {   \
            if ((BUF).head == cb_size(BUF) - 1) {  \
                (BUF).head = 0;  \
            } else {    \
                (BUF).head = ((BUF).head + 1);          \
            }   \
        } else {    \
            (BUF).occup = (BUF).occup + 1; \
        }   \
    } while(0)

#define cb_pop(BUF, ELEM)                                   \
    do {                                                        \
        if(!cb_empty((BUF))) {                                    \
            (ELEM) = (BUF).data[(BUF).head];                   \
            if ((BUF).head == cb_size(BUF) - 1) {  \
                (BUF).head = 0;  \
            } else {    \
                (BUF).head = ((BUF).head + 1);          \
            }   \
            (BUF).occup -= 1;                                    \
        }                                                       \
    } while(0)

#endif