Function call stack implementation. It can be used to implement a simple script interpreter.
Statement:
# Pragma once
Const int buffersize = 1024;
Const int growfactor = 2;
// This stack is used as call stack.
Class tstack {
PRIVATE:
Size_t size; // The stack Length
Size_t Pos; // The stack top position
Char * buffer; // The Buffer
PRIVATE:
Void push (void * D, size_t bytecount); // The implementation of push
Void * Pop (size_t bytecount); // The implementation of pop
Public:
Tstack (size_t _ size = buffersize, size_t _ Pos = 0); // initialize
Tstack (const tstack & O); // copy
Tstack & operator = (const tstack & O); // assignment
Void pushint (int I) {push (& I, sizeof (INT);} // push an int
Void pushlong (long l) {push (& L, sizeof (long);} // push a long
Void pushfloat (double F) {push (& F, sizeof (f);} // push a double
Void pushpointer (void * P) {push (p, sizeof (p ));}
// Int
Int popint () {return * (int *) Pop (sizeof (INT);} // pop an int
Long poplong () {return * (long *) Pop (sizeof (long);} // pop an int
Double * popfloat () {return (double *) Pop (sizeof (double);} // pop a double
Void * poppointer () {return POP (sizeof (void *));}
Void clear () {pos = 0 ;}
};
Implementation:
# Include "stdafx. H"
# Include "tstack. H"
# Include "New. H"
Void tstack: Push (void * D, size_t bytecount)
{
// If memory is not enough
// If run under multithread envionment,
// A lock or critical section shocould be added
If (Pos + bytecount> size)
{
Size_t oldsize = size;
Size * = growfactor;
Char * newbuffer = new char [size];
Memcpy (newbuffer, buffer, oldsize );
Delete buffer;
Buffer = newbuffer;
}
Memcpy (buffer + POs, D, bytecount );
Pos + = bytecount;
}
Void * tstack: Pop (size_t bytecount)
{
// Need synchronization for multithread Environment
Pos-= bytecount;
Return & buffer [POS];
}
Tstack: tstack (size_t _ size, size_t _ POS)
: Size (_ size ),
POs (_ POS ),
Buffer (New char [size])
{
}
Tstack: tstack (const tstack & O)
: Size (O. Size ),
POs (O. Pos)
{
Buffer = new char [size];
If (buffer! = NULL)
{
Memcpy (buffer, O. buffer, size );
}
}
Tstack & tstack: Operator = (const tstack & O)
{
If (this = & O)
Return * this;
This-> size = O. size;
This-> Pos = O. Pos;
If (buffer! = NULL)
{
Delete buffer;
}
Buffer = new char [This-> size];
If (buffer! = NULL)
{
Memcpy (buffer, O. buffer, this-> size );
}
Return * this;
}