C is a lot of fun. Lately ive been doing some development with an 8052 microcontroller. I have a situation where i need to buffer data coming in various interrupts, and i need to get to that data in the order it was received, and with minimal delay. I've implimented a ring buffer, which is 16 bytes in length and resides in near memory for fast access.
One of the fun things about c is trying to put together the most efficient algorithms you can come up with. This is the most efficient way i could figure to impliment a ring buffer:
[font=Courier]
char buf[16];
int head ;
int tail ;
void put ( char data ) {
if ( ++head > 16 )
head = 0 ;
if ( head == tail ) {
if ( ++tail > 16 )
tail = 0 ;
}
buf[head] = data ;
}
char snatch ( void ) {
char c ;
if ( head == tail ) {
// this queue is empty
} else {
if ( ++tail > 16 )
tail = 0 ;
}
c = buf[tail] ;
return c ;
}[/font]