#include #include #include "buffer.h" // implementation for a FIFO-buffer with ints // this very simple FIFO-buffer can only hold one int #define FIFO_SIZE 8 typedef struct FIFO_element_s { int value; void* nextElement; } FIFO_element_t; // shared variables within this file static FIFO_element_t* FIFO_FirstElement_p = NULL; static FIFO_element_t* FIFO_LastElement_p = NULL; static unsigned int FIFO_count = 0; bool FIFO_Full = false; /** incrementPointer * * add one and rotates if it overflows the buffersize */ unsigned int incrementPointer(unsigned int p) { p++; if (p == FIFO_SIZE) { p = 0; } return p; } bool buffer_put(int i) { bool ok = false; if ((FIFO_LastElement_p == NULL) && (FIFO_FirstElement_p == NULL)) { // buffer is empty. add first element FIFO_FirstElement_p = malloc(sizeof(FIFO_element_t)); if (FIFO_FirstElement_p != NULL) { FIFO_FirstElement_p->value = i; FIFO_FirstElement_p->nextElement = NULL; FIFO_LastElement_p = FIFO_FirstElement_p; FIFO_count++; ok = true; } else { FIFO_Full = true; } } else if ((FIFO_LastElement_p != NULL) && (FIFO_FirstElement_p != NULL)) { // add element to exsiting buffer FIFO_element_t* el = malloc(sizeof(FIFO_element_t)); if (el != NULL) { el->value = i; el->nextElement = NULL; FIFO_LastElement_p = el; FIFO_count++; ok = true; } else { FIFO_Full = true; } } else { // buffer is unhealthy. try to clear it and reinit //TODO: this while loop is unsave while (FIFO_FirstElement_p != NULL) { buffer_get(NULL); } if (FIFO_LastElement_p != NULL) { free(FIFO_LastElement_p); FIFO_LastElement_p = NULL; } buffer_put(i); ok = false; } return ok; } bool buffer_get(int *p) { bool ok = false; if (FIFO_FirstElement_p != NULL) { *p = FIFO_FirstElement_p->value; FIFO_element_t* next = FIFO_FirstElement_p->nextElement; free(FIFO_FirstElement_p); FIFO_count--; FIFO_Full = false; if (next == NULL) { // this was the last element in the buffer if (FIFO_LastElement_p == FIFO_FirstElement_p) { // clear last element becouse it's the same FIFO_LastElement_p = NULL; FIFO_count = 0; ok = true; } else if (FIFO_LastElement_p != NULL) { // buffer chain is broken; skip to last element FIFO_FirstElement_p = FIFO_LastElement_p; } else { // somehow the last element is NULL FIFO_count = 0; } } else { // set first element pointer to next element FIFO_FirstElement_p = next; ok = true; } } else { ok = false; } return ok; } bool buffer_is_full(void) { return FIFO_Full; } bool buffer_is_empty(void) { return ((FIFO_LastElement_p == NULL) && (FIFO_FirstElement_p == NULL)); } unsigned int number_of_elements_in_buffer() { return FIFO_count; }