Created
March 27, 2022 15:43
-
-
Save Rlesjak/1b5e59b69ffa910fbe5fc10944808253 to your computer and use it in GitHub Desktop.
Fifo Buffer - c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fifo.h> | |
// Buffer head is always kept on the first available(empty) element of the buffer | |
// it is not kept on the last written element! | |
void fifo_push(fifo_controller_t *controller, float value) | |
{ | |
// Write to current head | |
controller->arr[controller->head] = value; | |
// Circlar | |
if (++controller->head >= controller->len) | |
controller->head -= controller->len; | |
// Push tail forward if head reached it | |
if (controller->tail == controller->head) | |
controller->tail++; | |
} | |
// TODO: block read right after init | |
float fifo_read(fifo_controller_t *controller) | |
{ | |
float value = controller->arr[controller->tail]; | |
int lastTail = controller->tail; | |
// Circlar | |
if (++controller->tail >= controller->len) | |
controller->tail -= controller->len; | |
// Revert tail increment if it lands on head | |
if (controller->tail == controller->head) | |
controller->tail = lastTail; | |
return value; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// fifo.h | |
#pragma once | |
struct fifo_controller_t { | |
const int len; | |
float *arr; | |
int head; | |
int tail; | |
} ; | |
// Push float to buffer | |
void fifo_push(fifo_controller_t *controller, float value); | |
// Read float from buffer | |
float fifo_read(fifo_controller_t *controller); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment