@@ -39,6 +39,7 @@ class RingBufferN
3939 uint8_t _aucBuffer[N] ;
4040 volatile int _iHead ;
4141 volatile int _iTail ;
42+ volatile int _numElems;
4243
4344 public:
4445 RingBufferN ( void ) ;
@@ -67,16 +68,15 @@ RingBufferN<N>::RingBufferN( void )
6768template <int N>
6869void RingBufferN<N>::store_char( uint8_t c )
6970{
70- int i = nextIndex (_iHead);
71-
7271 // if we should be storing the received character into the location
7372 // just before the tail (meaning that the head would advance to the
7473 // current location of the tail), we're about to overflow the buffer
7574 // and so we don't write the character or advance the head.
76- if ( i != _iTail )
75+ if (! isFull () )
7776 {
7877 _aucBuffer[_iHead] = c ;
79- _iHead = i ;
78+ _iHead = nextIndex (_iHead);
79+ _numElems++;
8080 }
8181}
8282
@@ -85,6 +85,7 @@ void RingBufferN<N>::clear()
8585{
8686 _iHead = 0 ;
8787 _iTail = 0 ;
88+ _numElems = 0 ;
8889}
8990
9091template <int N>
@@ -95,28 +96,21 @@ int RingBufferN<N>::read_char()
9596
9697 uint8_t value = _aucBuffer[_iTail];
9798 _iTail = nextIndex (_iTail);
99+ _numElems--;
98100
99101 return value;
100102}
101103
102104template <int N>
103105int RingBufferN<N>::available()
104106{
105- int delta = _iHead - _iTail;
106-
107- if (delta < 0 )
108- return N + delta;
109- else
110- return delta;
107+ return _numElems;
111108}
112109
113110template <int N>
114111int RingBufferN<N>::availableForStore()
115112{
116- if (_iHead >= _iTail)
117- return N - 1 - _iHead + _iTail;
118- else
119- return _iTail - _iHead - 1 ;
113+ return (N - _numElems);
120114}
121115
122116template <int N>
@@ -137,7 +131,7 @@ int RingBufferN<N>::nextIndex(int index)
137131template <int N>
138132bool RingBufferN<N>::isFull()
139133{
140- return (nextIndex (_iHead) == _iTail );
134+ return (_numElems == N );
141135}
142136
143137}
0 commit comments