avr/packet-radio/src/packet_buffer.c

82 lines
2.3 KiB
C

/*
Copyright 2022, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of Savanni's AVR library.
This AVR library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This AVR library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this AVR library. If not, see <https://www.gnu.org/licenses/>.
*/
#include "radio.h"
#include "packet_buffer.h"
// #include <stdlib.h>
// #include <string.h>
size_t circular_next(size_t current, size_t max);
packet_buffer_t *packet_buffer_new(void) {
packet_buffer_t *buffer = malloc(sizeof(packet_buffer_t));
packet_buffer_init(buffer);
return buffer;
}
void packet_buffer_init(packet_buffer_t *buffer) {
buffer->count = 0;
buffer->bottom = 0;
buffer->top = 0;
}
packet_t *packet_buffer_enqueue(packet_buffer_t *self, packet_buffer_status_e *status) {
if (!IS_OK(status)) return NULL;
if (packet_buffer_is_full(self)) {
*status = packet_buffer_status_full;
return NULL;
}
packet_t *ptr = &self->buffer[self->top];
self->top = circular_next(self->top, 5);
self->count++;
return ptr;
}
packet_t *packet_buffer_head(packet_buffer_t *self, packet_buffer_status_e *status) {
if (!IS_OK(status)) return NULL;
if (packet_buffer_is_empty(self)) {
*status = packet_buffer_status_empty;
return NULL;
}
return &self->buffer[self->bottom];
}
void packet_buffer_dequeue(packet_buffer_t *self, packet_buffer_status_e *status) {
if (!IS_OK(status)) return;
if (packet_buffer_is_empty(self)) {
*status = packet_buffer_status_empty;
return;
}
self->bottom = circular_next(self->bottom, 5);
self->count--;
}
bool packet_buffer_is_full(packet_buffer_t *self) {
return self->count == 5;
}
bool packet_buffer_is_empty(packet_buffer_t *self) {
return self->count == 0;
}
size_t circular_next(size_t current, size_t max) {
current++;
return (current < max) ? current : 0;
}