summaryrefslogtreecommitdiffstats
path: root/lib/antlr/antlr/CircularQueue.h
blob: 89c593a1151921ffcd75ea290f17dd64a59c9de3 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#ifndef INC_CircularQueue_h__
#define INC_CircularQueue_h__

/* ANTLR Translator Generator
 * Project led by Terence Parr at http://www.jGuru.com
 * Software rights: http://www.antlr.org/license.html
 *
 * $Id$
 */

#include <antlr/config.h>
#include <antlr/Token.h>
#include <vector>
#include <cassert>

#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
namespace antlr {
#endif

// Resize every 5000 items
#define OFFSET_MAX_RESIZE 5000

template <class T>
class ANTLR_API CircularQueue {
public:
	CircularQueue()
	: storage()
	, m_offset(0)
	{
	}
	~CircularQueue()
	{
	}

	/// Clear the queue
	inline void clear( void )
	{
		m_offset = 0;
		storage.clear();
	}

	/// @todo this should use at or should have a check
	inline T elementAt( size_t idx ) const
	{
		return storage[idx+m_offset];
	}
	void removeFirst()
	{
		if (m_offset >= OFFSET_MAX_RESIZE)
		{
			storage.erase( storage.begin(), storage.begin() + m_offset + 1 );
			m_offset = 0;
		}
		else
			++m_offset;
	}
	inline void removeItems( size_t nb )
	{
		// it would be nice if we would not get called with nb > entries
		// (or to be precise when entries() == 0)
		// This case is possible when lexer/parser::recover() calls
		// consume+consumeUntil when the queue is empty.
		// In recover the consume says to prepare to read another
		// character/token. Then in the subsequent consumeUntil the
		// LA() call will trigger
		// syncConsume which calls this method *before* the same queue
		// has been sufficiently filled.
		if( nb > entries() )
			nb = entries();

		if (m_offset >= OFFSET_MAX_RESIZE)
		{
			storage.erase( storage.begin(), storage.begin() + m_offset + nb );
			m_offset = 0;
		}
		else
			m_offset += nb;
	}
	inline void append(const T& t)
	{
		storage.push_back(t);
	}
	inline size_t entries() const
	{
		return storage.size() - m_offset;
	}

private:
	ANTLR_USE_NAMESPACE(std)vector<T> storage;
	size_t m_offset;

	CircularQueue(const CircularQueue&);
	const CircularQueue& operator=(const CircularQueue&);
};

#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
}
#endif

#endif //INC_CircularQueue_h__