Reputation: 907
I have coded a simple ring buffer which has a ring size of 5 to store values of type A. Now I have to extend this buffer to store type B values(also 5 values).
To give an overview, I have defined the variables for read index and write index as global volatile and two functions for reading and writing on the ring buffer.
I only have to do : ring data = int read_ring_data()
and write_ring_data(int pass_new_data)
The volatile global variables help control the locations of read and write.
My question is, is there a way to reuse these read and write functions for extending it to a 2D buffer by simply re-dimensioning it? How do I implement it?
Upvotes: 1
Views: 2538
Reputation: 3399
You can still code in an object oriented style in C , simply using struct's as classes, and 'methods' are just functions that take a pointer to a class. I would create a general purpose 'ring-buffer' 'class' in C as follows..
typedef struct RingBuffer {
int elemSize;
int headIndex; // index to write
int tailIndex; // index to read
int maxIndex;
void* buffer;
}
RingBuffer;
// initialize a new ring-buffer object
void RingBuffer_Init(RingBuffer* rb, int elemSize, int maxNum) {
rb->elemSize=elemSize; rb->headIndex = 0; rb->tailIndex=0; rb->buffer = malloc(elemSize*maxNum);
rb->maxIndex=maxNum;
}
void RingBuffer_Read(RingBuffer* rb, void* dstItem){ // copy into buffer, update index
void* src=rb->buffer + rb->tailIndex*rb->elemSize;
memcpy(dstItem,src,rb->elemSize);
rb->tailIndex++; ....//wrapround, assert etc..
}
void RingBuffer_Write(RingBuffer* rb, const void * srcItem) { // copy from buffer,update indices
}// etc..
you'd have to take care of allocating the RingBuffer structs of course, some people might do that with some macro if they adopt a consistent naming scheme for 'init'(equiv of c++ constructor) and 'shutdown'/'release' functions
Of course there are many permutations.. it would be very easy to make a ring buffer into which you can read/write variable sized elements, perhaps writing the element size into the buffer at each point. it would certainly be possible to resize on the fly aswell, even change the element size.
Although the language support for creating data structures is more primitive in C than in C++, sometimes re-working a problem to use simple data structures can have performance benefits. Also treating data structures as simple blocks of memory with size passed as a parameter may cause less compiler inlining: compact code can have advantages as the default method to use outside of inner loops (i-cache coherency).
it would be possible to combine the 'Buffer Header' structure and the array data into one allocation, (just assume the buffer data follows the header structure in memory), which reduces the amount of pointer-dereferencing going on.
Upvotes: 1