@@ -39,6 +39,7 @@ class RingBufferN
39
39
uint8_t _aucBuffer[N] ;
40
40
volatile int _iHead ;
41
41
volatile int _iTail ;
42
+ volatile int _numElems;
42
43
43
44
public:
44
45
RingBufferN ( void ) ;
@@ -67,16 +68,15 @@ RingBufferN<N>::RingBufferN( void )
67
68
template <int N>
68
69
void RingBufferN<N>::store_char( uint8_t c )
69
70
{
70
- int i = nextIndex (_iHead);
71
-
72
71
// if we should be storing the received character into the location
73
72
// just before the tail (meaning that the head would advance to the
74
73
// current location of the tail), we're about to overflow the buffer
75
74
// and so we don't write the character or advance the head.
76
- if ( i != _iTail )
75
+ if (! isFull () )
77
76
{
78
77
_aucBuffer[_iHead] = c ;
79
- _iHead = i ;
78
+ _iHead = nextIndex (_iHead);
79
+ _numElems++;
80
80
}
81
81
}
82
82
@@ -85,6 +85,7 @@ void RingBufferN<N>::clear()
85
85
{
86
86
_iHead = 0 ;
87
87
_iTail = 0 ;
88
+ _numElems = 0 ;
88
89
}
89
90
90
91
template <int N>
@@ -95,28 +96,21 @@ int RingBufferN<N>::read_char()
95
96
96
97
uint8_t value = _aucBuffer[_iTail];
97
98
_iTail = nextIndex (_iTail);
99
+ _numElems--;
98
100
99
101
return value;
100
102
}
101
103
102
104
template <int N>
103
105
int RingBufferN<N>::available()
104
106
{
105
- int delta = _iHead - _iTail;
106
-
107
- if (delta < 0 )
108
- return N + delta;
109
- else
110
- return delta;
107
+ return _numElems;
111
108
}
112
109
113
110
template <int N>
114
111
int RingBufferN<N>::availableForStore()
115
112
{
116
- if (_iHead >= _iTail)
117
- return N - 1 - _iHead + _iTail;
118
- else
119
- return _iTail - _iHead - 1 ;
113
+ return (N - _numElems);
120
114
}
121
115
122
116
template <int N>
@@ -137,7 +131,7 @@ int RingBufferN<N>::nextIndex(int index)
137
131
template <int N>
138
132
bool RingBufferN<N>::isFull()
139
133
{
140
- return (nextIndex (_iHead) == _iTail );
134
+ return (_numElems == N );
141
135
}
142
136
143
137
}
0 commit comments