贅沢は敵ですっ!

http://d.hatena.ne.jp/w_o/20060419#p1
ネタ受け。組み込み屋ならスマートにムダを消せないとね。

struct q
{
	char *buf;
	int buflen;
	int head;
	int tail;
};

void init( struct q *q, char *buf, int len ) {
	q->head = 0;
	q->tail = 0;
	q->buf = buf;
	q->buflen = len;
}

void push( struct q *q, char c ) {
	if ( q->head == q->tail + q->len ) {
		/* 知らない */
		return;
	}

	q->buf[q->head%q->len] = c; //< これがミソ
	q->head++;
}

int pop( struct q *q ) {
	int ret;
	if ( q->head == q->tail )
		return -1; //< いや、これはどうかと・・・

	if ( q->tail == q->len ) {
		q->tail = 0;
		q->head -= q->len; //< これもミソ.
	}

	ret = q->buf[q->tail];
	q->tail++;
	return ret;
}

// ちなみに、pushが複雑になった分はsizeで取り戻す。
int size( struct q *q ) {
    return q->tail - q->head;
}
このブログに乗せているコードは引用を除き CC0 1.0 で提供します。