#include #include "Cirbuf.h" Cirbuf::Cirbuf(int s /* = D_SIZE */) { head = tail = length = 0; size = s; cb = new char[s]; // allocate buffer space } Cirbuf::~Cirbuf() { delete [] cb; // free up space } Cirbuf& Cirbuf::operator = (const Cirbuf& b) { if (&b == this) return(*this); head = 0; tail = length = b.length; if ( size != b.size ) { delete [] cb; size = b.size; cb = new char[size]; } for (int i=0 ; i < length ; i++) cb[i] = b.cb[(b.head + i) % size]; return(*this); } int Cirbuf::produce(char c) { if ( is_full() ) { cerr << "produce: buffer full\n"; return(-1); } cb[tail++] = c; length++; tail = mod(tail); return(0); } int Cirbuf::consume() { char c; if ( is_empty() ) { cerr << "consume: buffer empty\n"; return(-1); } c = cb[head++]; length--; head = mod(head); return(c); } int Cirbuf::next(char& c) { static int ind = -1; if ( ind == -1 ) ind = head; if ( ind == tail ) return(ind = -1); c = cb[ind++]; ind = mod(ind); return(ind); } CirbufIterator::CirbufIterator(Cirbuf& buf) : b(buf), ind(buf.head) { } int CirbufIterator::operator() (char& c) { if ( ind == b.tail ) return(0); c = b.cb[ind++]; ind = b.mod(ind); return(1); }