1#ifndef DELUGE_DRIVERS_UART_RX_BUFFER_H
2#define DELUGE_DRIVERS_UART_RX_BUFFER_H
9static inline uint32_t uartRingSpace(uint32_t size, uint32_t read_pos, uint32_t write_pos) {
10 return (read_pos - write_pos - 1) & (size - 1);
16static inline bool uartReplaceByteInRing(
volatile uint8_t* buffer, uint32_t size, uint32_t read_pos, uint32_t write_pos,
17 uint8_t value, uint8_t replacement) {
19 uint32_t mask = size - 1;
21 for (uint32_t pos = read_pos & mask; pos != write_pos; pos = (pos + 1) & mask) {
22 if (buffer[pos] == value) {
23 buffer[pos] = replacement;
38static inline bool uartReadStagedByte(
struct UartRxQueue* queue, uint8_t* value) {
42 *value = queue->bytes[queue->read_pos];
43 queue->read_pos = (queue->read_pos + 1) %
sizeof(queue->bytes);
48static inline void uartPrependStagedByte(
struct UartRxQueue* queue, uint8_t value) {
49 queue->read_pos = (queue->read_pos +
sizeof(queue->bytes) - 1) %
sizeof(queue->bytes);
50 queue->bytes[queue->read_pos] = value;
54static inline bool uartStagePendingBytes(
struct UartRxQueue* queue,
volatile uint8_t* buffer, uint32_t size,
55 uint32_t* read_pos, uint32_t write_pos, uint8_t value, uint8_t replacement) {
57 uint32_t retained = 0;
60 for (uint32_t offset = 0; offset < queue->count; ++offset) {
61 uint8_t
byte = queue->bytes[(queue->read_pos + offset) %
sizeof(queue->bytes)];
65 else if (
byte != replacement) {
66 queue->bytes[(queue->read_pos + retained++) %
sizeof(queue->bytes)] = byte;
69 queue->count = retained;
71 found = uartReplaceByteInRing(buffer, size, *read_pos, write_pos, value, replacement) || found;
72 uint32_t mask = size - 1;
74 while (*read_pos != write_pos) {
75 uint8_t
byte = buffer[*read_pos];
76 if (
byte != replacement) {
77 if (queue->count >=
sizeof(queue->bytes) - 1) {
80 queue->bytes[(queue->read_pos + queue->count++) %
sizeof(queue->bytes)] = byte;
82 *read_pos = (*read_pos + 1) & mask;
Definition rx_buffer.h:32