]> git.lyx.org Git - lyx.git/blob - src/support/limited_stack.h
* lyxfunctional.h: delete compare_memfun and helper classes
[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         typedef typename container_type::const_iterator const_iterator;
30
31         /// limit is the maximum size of the stack
32         limited_stack(size_type limit = 100) {
33                 limit_ = limit;
34         }
35
36         /// Return the top element.
37         value_type & top() {
38                 return c_.front();
39         }
40
41         /// Pop and throw away the top element.
42         void pop() {
43                 c_.pop_front();
44         }
45
46         /// Return true if the stack is empty.
47         bool empty() const {
48                 return c_.empty();
49         }
50
51         /// Clear all elements, deleting them.
52         void clear() {
53                 c_.clear();
54         }
55
56         /// Push an item on to the stack, deleting the
57         /// bottom item on overflow.
58         void push(value_type const & v) {
59                 c_.push_front(v);
60                 if (c_.size() > limit_) {
61                         c_.pop_back();
62                 }
63         }
64
65         /// Direct read access to intermediate elements.
66         T const & operator[](size_type pos) const {
67                 return c_[pos];
68         }
69
70         /// Read access to used size.
71         size_type size() const {
72                 return c_.size();
73         }
74
75         const_iterator begin() const {
76                 return c_.begin();
77         }
78
79         const_iterator end() const {
80                 return c_.end();
81         }
82
83 private:
84         /// Internal contents.
85         container_type c_;
86         /// The maximum number elements stored.
87         size_type limit_;
88 };
89
90 // Make pointer type an error.
91 template <typename T>
92 class limited_stack<T*>;
93
94 #endif // LIMITED_STACK_H