|
// Errors are 11.x
#include "global.h"
#include "ShortStack.h"
// Create the linked list
void ShortStack::Construct()
{
// initialise the values
_stack = (short*)malloc(MEMORYINCREMENT * 2);
if (_stack == NULL)
{
#ifdef INCLUDE_MSG_CRITICAL
#ifdef MINMEMORY
_platform->WriteMessage("11.1\n");
#else
_platform->WriteMessage("Error allocating memory for stack.\n");
#endif
#endif
_platform->Error(11);
}
_current = NULL;
_size = MEMORYINCREMENT;
}
// Push something onto the stacg
void ShortStack::Push(short value)
{
// check if we have enough space
if (_current != NULL && ((_current - _stack)/2 + 1 == _size))
{
// grow the stack
// allocate a larger space
short* newstack = (short*)malloc(_size + MEMORYINCREMENT);
if (newstack == NULL)
{
#ifdef INCLUDE_MSG_CRITICAL
#ifdef MINMEMORY
_platform->WriteMessage("11.2\n");
#else
_platform->WriteMessage("Error allocating memory for growing stack.\n");
#endif
#endif
_platform->Error(11);
}
// copy across from the old small stack
memcpy(newstack, _stack, _size * 2);
// move across the current pointer
_current = newstack + (_current - _stack);
// release the old one
free(_stack);
// now remember the new stack
_stack = newstack;
_size = _size + MEMORYINCREMENT;
}
// now put it on the stack
if (_current == NULL)
{
_current = _stack;
}
else
{
_current++;
}
*_current = value;
}
// pop the top item from the stack
short ShortStack::Pop()
{
// check if there is anything in the stack
if (_current == NULL)
{
#ifdef INCLUDE_MSG_CRITICAL
#ifdef MINMEMORY
_platform->WriteMessage("11.3\n");
#else
_platform->WriteMessage("Trying to pop a value from an empty stack.\n");
#endif
#endif
_platform->Error(11);
}
// take it off the top and adjust the stack
short ret = *_current;
_current--;
if (_current < _stack)
{
_current = NULL;
}
return ret;
}
#if defined(PC) || defined(RASPBERRY)
// get the number of items in the stack.
byte ShortStack::Count () const
{
if (_current == NULL)
{
return 0;
}
// return the size
return (byte)((_current - _stack + 2) / 2);
}
#endif
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.