From d63d2c3c6cbbd574dda4f8b00ebe6c661735edd5 Mon Sep 17 00:00:00 2001 From: Felix Domke Date: Fri, 17 Oct 2003 15:36:42 +0000 Subject: import of enigma2 --- lib/base/ringbuffer.h | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 lib/base/ringbuffer.h (limited to 'lib/base/ringbuffer.h') diff --git a/lib/base/ringbuffer.h b/lib/base/ringbuffer.h new file mode 100644 index 00000000..f2cd9058 --- /dev/null +++ b/lib/base/ringbuffer.h @@ -0,0 +1,109 @@ +#ifndef QueueRingBufferH +#define QueueRingBufferH + +template +class queueRingBuffer +{ + template + struct link + { + link ( const A &val ) + :value(val) + {} + A value; + link *nextLink; + link *prevLink; + }; + + link *lastFilled; + link *lastFree; + unsigned int max; + int count; +public: + queueRingBuffer( unsigned int max ); + ~queueRingBuffer(); + int size() { return count; } + T& queueRingBuffer::dequeue(); + T& queueRingBuffer::current(); + void queueRingBuffer::enqueue( const T &val ); +}; + +template +queueRingBuffer::queueRingBuffer( unsigned int max ) +{ + // constructor for queues based on ring buffers + // create the first link + T initialvalue; + lastFree = new link( initialvalue ); + lastFilled = lastFree; + // make value point to itself + lastFilled->nextLink = lastFilled; + lastFilled->prevLink = lastFilled; + // now add the remainder of the elements + while ( max-- > 0 ) + { + link * newLink = new link( initialvalue ); + newLink->prevLink = lastFilled; + newLink->nextLink = lastFilled->nextLink; + lastFilled->nextLink->prevLink = newLink; + lastFilled->nextLink = newLink; + } +} + +template +queueRingBuffer::~queueRingBuffer() +{ + // delete all memory associated with ring buffer + link * p = lastFree; + link * next; + + // walk around the circle deleting nodes + while( p->nextLink != lastFree ) + { + next = p->nextLink; + delete p; + p = next; + } +} + +template +T& queueRingBuffer::dequeue() +{ + // remove element form front of queue + // advance last free position + lastFree = lastFree->nextLink; + count--; + // return value stored in last free position + return lastFree->value; +} + +template +T& queueRingBuffer::current() +{ + // return value stored in current + return lastFree->nextLink->value; +} + +template +void queueRingBuffer::enqueue( const T &val ) +{ + // add new element to end of queue buffer + // first check for potential overflow + if( lastFilled->nextLink == lastFree ) + { + eDebug("increase size %d", count); + link * newLink = new link( val ); + newLink->prevLink = lastFilled; + newLink->nextLink = lastFilled->nextLink; + lastFilled->nextLink->prevLink = newLink; + lastFilled->nextLink = newLink; + } + else + { + // simply advance the last filled pointer + lastFilled = lastFilled->nextLink; + lastFilled->value = val; + } + count++; +} +#endif -- cgit v1.2.3