]> git.tdb.fi Git - model-railway-devices.git/blob - common/ringbuffer.h
Make upload device configurable
[model-railway-devices.git] / common / ringbuffer.h
1 #ifndef RINGBUFFER_H_
2 #define RINGBUFFER_H_
3
4 #define RINGBUFFER(name, size) uint8_t name[(size)+4] = { (size)+1, 0, 0 }
5
6 static inline uint8_t ringbuffer_size(const uint8_t *buffer)
7 {
8         return buffer[0]-1;
9 }
10
11 static inline uint8_t ringbuffer_fill(const uint8_t *buffer)
12 {
13         const uint8_t size = buffer[0];
14         uint8_t head = buffer[1];
15         uint8_t tail = buffer[2];
16         if(head<tail)
17                 head += size;
18         return head-tail;
19 }
20
21 static inline uint8_t ringbuffer_space(const uint8_t *buffer)
22 {
23         return ringbuffer_size(buffer)-ringbuffer_fill(buffer);
24 }
25
26 static inline void ringbuffer_push(uint8_t *buffer, uint8_t value)
27 {
28         const uint8_t size = buffer[0];
29         uint8_t head = buffer[1];
30         buffer[3+head] = value;
31         ++head;
32         if(head>=size)
33                 head -= size;
34         buffer[1] = head;
35 }
36
37 static inline void ringbuffer_blocking_push(uint8_t *buffer, uint8_t value)
38 {
39         const uint8_t size = buffer[0];
40         uint8_t next_head = buffer[1]+1;
41         if(next_head>=size)
42                 next_head -= size;
43         const volatile uint8_t *tail = buffer+2;
44         while(next_head==*tail) ;
45         ringbuffer_push(buffer, value);
46 }
47
48 static inline uint8_t ringbuffer_pop(uint8_t *buffer)
49 {
50         const uint8_t size = buffer[0];
51         uint8_t tail = buffer[2];
52         uint8_t value = buffer[3+tail];
53         ++tail;
54         if(tail>=size)
55                 tail -= size;
56         buffer[2] = tail;
57         return value;
58 }
59
60 static inline uint8_t ringbuffer_blocking_pop(uint8_t *buffer)
61 {
62         const volatile uint8_t *head = buffer+1;
63         uint8_t tail = buffer[2];
64         while(*head==tail) ;
65         return ringbuffer_pop(buffer);
66 }
67
68 #endif