]> git.lyx.org Git - lyx.git/blob - src/support/limited_stack.h
319a05c2d5df8316772c0fd0e94c6fa2c98ebb94
[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_.empty();
48         }
49
50         /// Clear all elements, deleting them.
51         void clear() {
52                 c_.clear();
53         }
54
55         /// Push an item on to the stack, deleting the
56         /// bottom item on overflow.
57         void push(value_type const & v) {
58                 c_.push_front(v);
59                 if (c_.size() > limit_) {
60                         c_.pop_back();
61                 }
62         }
63
64         /// Direct read access to intermediate elements.
65         T const & operator[](size_type pos) const {
66                 return c_[pos];
67         }
68
69         /// Read access to used size.
70         size_type size() const {
71                 return c_.size();
72         }
73 private:
74         /// Internal contents.
75         container_type c_;
76         /// The maximum number elements stored.
77         size_type limit_;
78 };
79
80 // Make pointer type an error.
81 template <typename T>
82 class limited_stack<T*>;
83
84 #endif // LIMITED_STACK_H