stmtQueue.c 2.65 KB
#include <malloc.h>
#include <string.h>

#include <ident.h>
#include <statement.h>
#include <block.h>

#include <stmtQueue.h>

/* give the queue an initial size for 10 statements */
#define QUEUE_GROW_SIZE		10


struct stmtQueue
{
	s_stmt ** stmts;		/* a dynamically growing array of statements. */

	unsigned int size;	/* the actual size of the array in statements */
	unsigned int maxIdx;	/* the maximum index used in the array. */
};

	s_stmtQueue *
stmtQueueNew (void)
{
	s_stmtQueue * new = (s_stmtQueue *) malloc (sizeof (s_stmtQueue));

	new->size   = QUEUE_GROW_SIZE;
	new->maxIdx = 0;
	new->stmts  = (s_stmt **) calloc (sizeof (s_stmt *), new->size);
	memset (new->stmts, 0, sizeof (s_stmt *) * new->size);

	return new;
}

/*
 * This concat does not change a or b, as opposed to the c strcat function
 */
	s_stmtQueue *
stmtQueueConcat (s_stmtQueue * a, s_stmtQueue * b)
{
	s_stmtQueue * new = (s_stmtQueue *) malloc (sizeof (s_stmtQueue));

	new->size   = a->size + b->size;
	new->maxIdx = a->maxIdx + b->maxIdx;
	new->stmts  = (s_stmt **) calloc (sizeof (s_stmt *), new->size);
	memset (new->stmts, 0, sizeof (s_stmt *) * new->size);

	memcpy (new->stmts, a->stmts, sizeof (s_stmt *) * a->maxIdx);
	memcpy (&(new->stmts[a->maxIdx]), b->stmts, sizeof (s_stmt *) * b->maxIdx);

	return new;
}

	void
stmtQueueFree (s_stmtQueue * sQueue)
{
	unsigned int i;

	if (sQueue == NULL)
		return;

	/* freeing the queue is the final step. All stmts should be freed too! */
	for (i = 0; i < sQueue->maxIdx; i++)
		stmtFree (sQueue->stmts [i]);

	free (sQueue->stmts);
	free (sQueue);
}

	void
stmtQueueEnqueue (s_stmtQueue * sQueue, s_stmt * stmt)
{
	if (sQueue->maxIdx >= sQueue->size)
	{
		s_stmt **    stmtsOld = sQueue->stmts;
		unsigned int newSize  = sQueue->size + QUEUE_GROW_SIZE;

		sQueue->stmts = (s_stmt **) calloc (sizeof (s_stmt *), newSize);
		memcpy (sQueue->stmts, stmtsOld, sizeof (s_stmt **) * sQueue->size);
		free (stmtsOld); /* free the old queue but keep the statements */
		memset (
				&(sQueue->stmts[sQueue->size]), 
				0, 
				sizeof (s_stmt **) * QUEUE_GROW_SIZE);
		sQueue->size = newSize;;
	}

	sQueue->stmts[sQueue->maxIdx ++] = stmt;
}

	s_stmt *
stmtQueueDequeue (s_stmtQueue * sQueue)
{
	s_stmt * ret = sQueue->stmts[sQueue->maxIdx - 1];

	sQueue->stmts[-- sQueue->maxIdx] = NULL;

	return ret;
}

	s_stmt *
stmtQueueGet (s_stmtQueue * sQueue, unsigned int idx)
{
	if (idx < sQueue->size)
		return sQueue->stmts [idx];
	else
		return NULL;
}

	void
stmtQueueDo (s_stmtQueue * sQueue)
{
	int i;

	if (sQueue == NULL)
		return;

	for (i = 0; i < sQueue->maxIdx; i++)
		stmtDo (sQueue->stmts[i]);
}

	unsigned
	int
stmtQueueGetSize (s_stmtQueue * sQueue)
{
	return sQueue->size;
}