C言語 リングバッファ(個人用途)

C言語でリングバッファ。個人用。

#include <stdio.h>
#include <string.h>

#define BUFFSIZE 3

typedef struct {
  int head;
  int tail;
  int buff[BUFFSIZE];
} RingBuff;

void init_rbuff(RingBuff *b);
void set_rbuff(RingBuff *b, int val);
void print_rbuff(RingBuff *b);

int main(void) {

  RingBuff rbuff;
  int i;

  init_rbuff(&rbuff);

  puts("first");
  for (i=1; i<=5; i++) {
    set_rbuff(&rbuff, i);
  }
  print_rbuff(&rbuff);

  puts("second");
  for (i=1; i<=5; i++) {
    set_rbuff(&rbuff, i);
  }
  print_rbuff(&rbuff);

  return 0;
}

void init_rbuff(RingBuff *b) {

  b->head = 0;
  b->tail = 0;
  memset(b->buff, 0, sizeof(b->buff));

  return;
}

void set_rbuff(RingBuff *b, int val) {

  if (b->head == b->tail && b->buff[b->head] != 0) {
    b->head = (b->head + 1) % BUFFSIZE;
  }

  b->buff[b->tail] = val;
  b->tail = (b->tail + 1) % BUFFSIZE;

  return;
}

void print_rbuff(RingBuff *b) {

  int i, j;
  for (i=b->head; i<(b->head+BUFFSIZE); i++) {
    j = i % BUFFSIZE;
    printf("b[%d]: %d\n", j, b->buff[j]);
  }

  return;
}