add unified compile target
[avr_work.git] / common / list.c
blob2b1d7dc3dd59a90f7a47525a2790ce9ef9e62f38
1 /* list.c
2 functions for static list implimentation.
3 */
4 #include <stdio.h>
5 #include <stdint.h>
6 #include <stdbool.h>
8 #include "list.h"
10 #define likely(x) __builtin_expect((x),1)
11 #define unlikely(x) __builtin_expect((x),0)
13 #define LIST_ERROR(...) fprintf(stderr,"ERROR: %s:%s():%d \n",__FILE__,__FUNCTION__,__LINE__);
16 list_base_t list_pop_front(list_t *l) {
17 if ( unlikely( list_empty(l) ) ) {
18 LIST_ERROR();
19 return 0;
22 list_base_t head = l->buffer[ l->first ];
24 l->first++;
25 if ( l->first >= l->sz )
26 l->first = 0;
28 --(l->ct);
30 return head;
33 list_base_t list_pop_back(list_t *l) {
34 if ( unlikely( list_empty(l) ) ) {
35 LIST_ERROR();
36 return 0;
39 l->ct--;
41 l->end--;
42 if ( l->end >= l->sz) // if overflowed
43 l->end = l->sz - 1;
45 list_base_t last = l->buffer[l->end];
47 return last;
50 list_error_t list_push_front(list_t *l, list_base_t x) {
51 if ( unlikely( list_full(l) ) ){
52 LIST_ERROR();
53 return -1;
56 l->ct++;
58 l->first--;
59 if ( l->first >= l->sz ) // if overflowed
60 l->first = l->sz - 1;
62 l->buffer[ l->first ] = x;
64 return 0;
67 list_error_t list_push_back(list_t *l, list_base_t x) {
68 if ( unlikely( list_full(l) ) ){
69 LIST_ERROR();
70 return -1;
73 l->ct++;
75 l->buffer[ l->end ] = x;
77 l->end++;
78 if ( l->end >= l->sz )
79 l->end = 0;
81 return 0;
84 list_error_t list_push_back_o(list_t *l, list_base_t x) {
85 l->buffer[ l->end ] = x;
87 l->end++;
88 if ( l->end >= l->sz )
89 l->end = 0;
91 if (!list_full(l))
92 ++(l->ct);
94 return 0;
97 list_base_t list_peek_front(list_t *l) {
98 if ( unlikely( list_empty(l) ) ) {
99 LIST_ERROR();
100 return 0;
103 return l->buffer[l->first];
105 list_base_t list_peek_back(list_t *l) {
106 if ( unlikely( list_empty(l) ) ) {
107 LIST_ERROR();
108 return 0;
111 list_index_t last = l->end-1;
112 if (last >= l->sz) {
113 last = l->sz-1;
116 return l->buffer[last];
121 list_base_t list_peek(list_t *l, list_index_t index) {
122 if ( unlikely( index > l->ct ) ) {
123 LIST_ERROR();
124 return 0;
127 uint8_t sum = l->first + index;
128 uint8_t diff = l->first - index;
130 if ( sum < l->first ) {
131 //XXX: damn overflow.
134 if ( sum >= l->sz ) {
139 void list_flush(list_t *list) {
140 list->first = list->end;
141 list->ct = 0;
144 bool list_empty(list_t *list) {
145 if ( unlikely( list->ct == 0 ) ) return true;
146 else return false;
149 bool list_full(list_t *list) {
150 if ( unlikely( list->ct >= list->sz ) ) return true;
151 else return false;