#include "ringBuffer.h"

ringBuffer_t bufferU1; // UART1 receive buffer
ringBuffer_t bufferU3; // UART3 receive buffer

static uint16_t RingBuff_NextIndex(uint16_t index) {
	index++;
	return (index == RING_BUFFER_SIZE) ? 0U : index;
}

uint8_t RingBuff_Write(ringBuffer_t *buffer, uint8_t data) {

	uint16_t next_tail;

	if (buffer == NULL) {
		return 1U;
	}

	next_tail = RingBuff_NextIndex(buffer->tail);

	/* Only the consumer may change head. Dropping the incoming byte preserves
	 * the single-producer/single-consumer concurrency contract. */
	if (next_tail == buffer->head) {
		return 1U;
	}

	buffer->data[buffer->tail] = data;
	buffer->tail = next_tail;

	return 0U;

}

uint8_t RingBuff_Read(ringBuffer_t *buffer, uint8_t *data) {

	uint16_t head;

	if ((buffer == NULL) || (data == NULL)) {
		return 1U;
	}

	head = buffer->head;

	// Equal indices mean there is no unread byte
	if (head == buffer->tail) {
		return 1U;
	}

	*data = buffer->data[head];
	buffer->head = RingBuff_NextIndex(head);

	return 0U;

}
