x893 - Okay, I agree with you. That is the code I see for the usart Serial.
The usart code uses the code in libmaple/ring_buffer.h
Would you please check my logic?
That part of libmaple looks like it contains bug to me in the ring_buffer.h code.
/libmaple/wirish/comm/HardwareSerial.cpp contains:
HardwareSerial Serial2(USART2, 2250000UL, GPIOA_BASE, 2, 3, TIMER2, 3);
and defines:
uint32 HardwareSerial::available(void) {
return usart_data_available(usart_num);
}
/libmaple/libmaple/usart.h contains:
static inline uint32 usart_data_available(uint8 usart_num) {
return rb_full_count(&usart_dev_table[usart_num].rb);
}
ring_buffer.h contains:
static inline uint32 rb_full_count(ring_buffer *rb) {
return rb->tail - rb->head;
}
and
typedef struct ring_buffer {
uint32 head;
uint32 tail;
uint8 size;
uint8 *buf;
} ring_buffer;
The size of the buffer is constrained to be a power of 2:
static inline void rb_init(ring_buffer *rb, uint8 size, uint8 *buf) {
ASSERT(IS_POWER_OF_TWO(size));
rb->head = 0;
rb->tail = 0;
rb->size = size;
rb->buf = buf;
}
Let's imagine the buffer is 64 bytes long, a power of 2.
Characters are added, and removed until head = 17 (characters are added to the tail, and removed from the head)
Some more charactera are added, filling the buffer, and tail is wrapped around to the start of the buffer, and becomes 0.
rb_full_count(...) will return 17
Let's repeat the experiment with the buffer size 128, another power of 2.
A similar sequence of events, but more characters are written before the wrap around.
So head = 17, and tail = 0
rb_full_count(...) will still return 17
so even though the buffer is bigger, the number of characters is the same.
Do the same thought-experiment where head gets to 3 short of the size of the buffer, and then tail wraps to 0. Even though there are fewer characters, the value from rb_full_count(...) is even bigger.
Does that seem correct?
I think this is a bug. It should return the number of characters in the buffer.