Rewrite RingBuffer class
- Dominant language
- Java
- Stars
- 14.6k
- Forks
- 7k
- PR merge metrics
- No merged PRs in 30d
Description
What's up with UART classes going in there accessing member variables of `RingBuffer` class?
Here is a rewritten `RingBuffer` class that no longer allow access to its member variables but can be used too. All condition checking can be rewritten as spin locking on the return value of `putchar` and `getchar`
``` C++
/*
* RingBuffer.h
*
* Created on: 2016年10月6日
* Author: max
*/
#ifndef _RING_BUFFER_
#define _RING_BUFFER_
#include
// Define constants and variables for buffering incoming serial data. We're
// using a ring buffer, in which head is the index of the location
// to which to write the next incoming character and tail is the index of the
// location from which to read.
#ifndef SERIAL_BUFFER_SIZE
#define SERIAL_BUFFER_SIZE 128
#endif
#ifdef __cplusplus
class RingBuffer
{
private:
volatile uint8_t buffer[SERIAL_BUFFER_SIZE] ;
volatile uintptr_t head ;
volatile uintptr_t tail ;
public:
RingBuffer(void);
int putchar(uint8_t c);
int getchar(void);
int peekchar(void);
size_t flen(void);
};
#endif
#endif /* _RING_BUFFER_ */
#include
#include
RingBuffer::RingBuffer(void)
{
memset(static_cast(buffer), 0, SERIAL_BUFFER_SIZE);
head = 0;
tail = 0;
}
int RingBuffer::putchar(uint8_t c)
{
uintptr_t i = (head + 1) % SERIAL_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != tail)
{
buffer[head] = c;
head = i;
return 0;
}
else
{
return -1;
}
}
int RingBuffer::getchar(void)
{
int ch = getchar();
if (ch >= 0)
{
tail = (tail + 1) % SERIAL_BUFFER_SIZE;
}
return ch;
}
int RingBuffer::peekchar(void)
{
if (tail != head)
{
return buffer[tail];
}
else
{
return -1;
}
}
size_t RingBuffer::flen(void)
{
return (SERIAL_BUFFER_SIZE + head - tail) % SERIAL_BUFFER_SIZE;
}
```
Contributor guide
Research direction
Start by locating the UART classes and the existing RingBuffer implementation referenced in the issue, then compare their direct member access with the proposed RingBuffer.h interface. Check how putchar, getchar, peekchar, and flen are used and whether the proposed return-value checks fit those callers. Done means the UART code no longer accesses RingBuffer members directly and the revised behavior is verified.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- embedded-iot
- Issue type
- Refactor
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100