/* * Stack.c * Author: Hannah C. Tang (hctang@cs) * * Implementation of public and private functions for the * Reader struct * * $Id: Stack.c,v 1.1 2001/12/18 00:24:16 cse466_t Exp $ * */ #include #include #include "Reader.h" #include "Stack.h" #include "common.h" /* * PRIVATE: * * Stack struct, Stack_element struct, method for resizing * internal array, various constants */ struct Stack_element { unsigned int index; enum Reader_TokenType t; unsigned int arg; }; struct Stack { struct Stack_element *pArray; unsigned int stackSize; unsigned int stackCapacity; }; static int INITIAL_STACK_CAP = 8; void Stack_resizeArray( struct Stack *pS ); struct Stack* Stack_malloc( void ) { struct Stack *pS = ( struct Stack* ) malloc( sizeof( struct Stack ) ); if( pS == NULL ) { fprintf( stderr, "Out of memory allocating a Stack!\n" ); exit( 0 ); } pS->pArray = ( struct Stack_element* ) malloc( sizeof( struct Stack_element ) * INITIAL_STACK_CAP ); pS->stackSize = 0; pS->stackCapacity = INITIAL_STACK_CAP; return pS; } void Stack_free( struct Stack *pS ) { if( pS != NULL ) { if( pS->pArray != NULL ) { free( pS->pArray ); } free( pS ); } } Bool Stack_push( struct Stack *pS, unsigned int index, enum Reader_TokenType t, unsigned int arg ) { /* Resize the array if necessary */ while( pS->stackSize >= pS->stackCapacity ) { Stack_resizeArray( pS ); } /* Push the tuple onto the stack */ pS->pArray[ pS->stackSize ].index = index; pS->pArray[ pS->stackSize ].t = t; pS->pArray[ pS->stackSize ].arg = arg; pS->stackSize++; return Bool_true; } Bool Stack_pop( struct Stack *pS, unsigned int *pIndex, enum Reader_TokenType *pT, unsigned int *pArg ) { struct Stack_element se; if( Stack_isEmpty( pS ) ) { fprintf( stderr, "Error: popping from empty stack\n" ); } se = pS->pArray[ pS->stackSize - 1 ]; if( pIndex != NULL ) { *pIndex = se.index; } if( pT != NULL ) { *pT = se.t; } if( pArg != NULL ) { *pArg = se.arg; } pS->stackSize--; return Bool_true; } unsigned int Stack_getNumElements( const struct Stack *pS ) { return pS->stackSize; } Bool Stack_isEmpty( const struct Stack *pS ) { return pS->stackSize == 0 ? Bool_true : Bool_false; } void Stack_resizeArray( struct Stack *pS ) { /* Double the capacity of the current array */ unsigned int origCapacity = pS->stackCapacity; unsigned int newCapacity = origCapacity * 2; pS->pArray = realloc( pS->pArray, newCapacity * sizeof( struct Stack_element ) ); pS->stackCapacity = newCapacity; }