]> git.lyx.org Git - lyx.git/blob - src/support/limited_stack.h
fa05691ce5411232c2002dfa63d543aec75db3fa
[lyx.git] / src / support / limited_stack.h
1 // -*- C++ -*-
2 /**
3  * \file limited_stack.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author John Levon
8  *
9  * Full author contact details are available in file CREDITS
10  */
11
12 #ifndef LIMITED_STACK_H
13 #define LIMITED_STACK_H
14
15 #include <deque>
16
17 /**
18  * limited_stack - a stack of limited size
19  *
20  * Like a normal stack, but elements falling out
21  * of the bottom are destructed.
22  */
23 template <typename T>
24 class limited_stack {
25 public:
26         typedef std::deque<T> container_type;
27         typedef typename container_type::value_type value_type;
28         typedef typename container_type::size_type size_type;
29
30         /// limit is the maximum size of the stack
31         limited_stack(size_type limit = 100) {
32                 limit_ = limit;
33         }
34
35         /// return the top element
36         value_type top() {
37                 return c_.front();
38         }
39
40         /// pop and throw away the top element
41         void pop() {
42                 c_.pop_front();
43         }
44
45         /// return true if the stack is empty
46         bool empty() const {
47                 return c_.size() == 0;
48         }
49
50         /// clear all elements, deleting them
51         void clear() {
52                 while (!c_.empty()) {
53                         c_.pop_back();
54                 }
55         }
56
57         /// push an item on to the stack, deleting the
58         /// bottom item on overflow.
59         void push(value_type const & v) {
60                 c_.push_front(v);
61                 if (c_.size() > limit_) {
62                         c_.pop_back();
63                 }
64         }
65
66         /// direct read access to intermediate elements
67         T const & operator[](size_type pos) const {
68                 return c_[pos];
69         }
70
71         /// read access to used size
72         size_type size() const {
73                 return c_.size();
74         }
75 private:
76         /// internal contents
77         container_type c_;
78         /// the maximum number elements stored
79         size_type limit_;
80 };
81
82 // make pointer type an error.
83 template <typename T>
84 class limited_stack<T*>;
85
86 #endif // LIMITED_STACK_H