#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;

const int BSIZE = 8;

typedef struct 
{
    int head;
    int tail;
    int *buffer; 
} QUEUE; 

void Queue_Init(QUEUE *);
void Queue_Destroy(QUEUE *);
bool Queue_Is_Empty(QUEUE *);
bool Queue_Is_Full(QUEUE *);
bool Queue_Get(QUEUE *, int *data);
bool Queue_Put(QUEUE *, int data);

int main(int argc, char* argv[])
{
    int i=0;
    int data; 
    QUEUE queue; 

    Queue_Init(&queue); 

    cout << "Fill the queue with data ...   ";

    while (Queue_Put(&queue,i))
       cout << i++ << " ";

    assert(Queue_Is_Full(&queue));

    cout << endl << "Extract data from the queue... ";

    while (Queue_Get(&queue, &data))
       cout << data << " "; 

    cout << endl;

    assert(Queue_Is_Empty(&queue));

    Queue_Destroy(&queue);

    system("pause");
    return 0;
} 

void Queue_Init(QUEUE *queue)
{
    queue->head = 0;
    queue->tail = 0;
    queue->buffer = (int *) malloc(sizeof(int)*BSIZE);
} 

void Queue_Destroy(QUEUE *queue)
{
    if (queue->buffer != 0)
    {
        free(queue->buffer);
        queue->buffer = 0;
    }
} 

bool Queue_Is_Empty(QUEUE *queue)
{
    if(queue->head == queue->tail)
        return true;
    return false; 
} 

bool Queue_Is_Full(QUEUE *queue)
{
    if((queue->tail+1)%BSIZE==queue->head)
        return true;
    return false; 
} 

bool Queue_Get(QUEUE *queue, int *data)
{
    // 如果 buffer 裡沒有東西, 請回傳 false
    if (Queue_Is_Empty(queue))
        return false;
    else
    {
        *data = queue->buffer[queue->head];
        queue->head = (queue->head+1) % BSIZE;
    }
    // 請由 buffer 中 (queue 的最前端) 取出資料

    return true;
} 

bool Queue_Put(QUEUE *queue, int data)
{
    if(Queue_Is_Full(queue))
        return false; 

    queue->buffer[queue->tail] = data; 

    queue->tail=(queue->tail+1)%BSIZE; 

    return true;
}