aboutsummaryrefslogtreecommitdiff
path: root/src/stable/stack.h
blob: f60907dec573d5e7c8e5df13092f437573f4765b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
 * Copyright (C) 2007-2012 Xagasoft, All rights reserved.
 *
 * This file is part of the libbu++ library and is released under the
 * terms of the license contained in the file LICENSE.
 */

#ifndef BU_STACK_H
#define BU_STACK_H

#include <memory>
#include "bu/config.h"

namespace Bu
{
	template<typename value, typename valuealloc=std::allocator<value> >
	class Stack
	{
	private:
		typedef struct Chunk
		{
			value *pValue;
			Chunk *pPrev;
		} Chunk;
	public:
		Stack() :
			pTop( NULL )
		{
		}

		virtual ~Stack()
		{
		}

		void push( const value &v )
		{
			Chunk *pChnk = new Chunk;
			pChnk->pValue = va.allocate( 1 );
			va.construct( pChnk->pValue, v );
			pChnk->pPrev = pTop;
			pTop = pChnk;
		}

		value &peek()
		{
			return *pTop->pValue;
		}
		
		value &top()
		{
			return *pTop->pValue;
		}

		value pop()
		{
			value ret( *pTop->pValue );
			
			Chunk *pChnk = pTop;
			pTop = pTop->pPrev;

			va.destroy( pChnk->pValue );
			va.deallocate( pChnk->pValue, 1 );
			delete pChnk;

			return ret;
		}

		void clear()
		{
			while( !isEmpty() )
				pop();
		}

		bool isEmpty()
		{
			return pTop == NULL;
		}

	private:
		Chunk *pTop;
		valuealloc va;
	};
}

#endif