Merge branch 'patch' of ssh://github.com/svost/novacoin into svost-patch
[novacoin.git] / src / mruset.h
1 // Copyright (c) 2012 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 #ifndef BITCOIN_MRUSET_H
5 #define BITCOIN_MRUSET_H
6
7 #include <set>
8 #include <deque>
9
10 /** STL-like set container that only keeps the most recent N elements. */
11 template <typename T> class mruset
12 {
13 public:
14     typedef T key_type;
15     typedef T value_type;
16     typedef typename std::set<T>::iterator iterator;
17     typedef typename std::set<T>::const_iterator const_iterator;
18     typedef typename std::set<T>::size_type size_type;
19
20 protected:
21     std::set<T> set;
22     std::deque<T> queue;
23     size_type nMaxSize;
24
25 public:
26     mruset(size_type nMaxSizeIn = 0) { nMaxSize = nMaxSizeIn; }
27     iterator begin() const { return set.begin(); }
28     iterator end() const { return set.end(); }
29     size_type size() const { return set.size(); }
30     bool empty() const { return set.empty(); }
31     iterator find(const key_type& k) const { return set.find(k); }
32     size_type count(const key_type& k) const { return set.count(k); }
33     bool inline friend operator==(const mruset<T>& a, const mruset<T>& b) { return a.set == b.set; }
34     bool inline friend operator==(const mruset<T>& a, const std::set<T>& b) { return a.set == b; }
35     bool inline friend operator<(const mruset<T>& a, const mruset<T>& b) { return a.set < b.set; }
36     std::pair<iterator, bool> insert(const key_type& x)
37     {
38         std::pair<iterator, bool> ret = set.insert(x);
39         if (ret.second)
40         {
41             if (nMaxSize && queue.size() == nMaxSize)
42             {
43                 set.erase(queue.front());
44                 queue.pop_front();
45             }
46             queue.push_back(x);
47         }
48         return ret;
49     }
50     size_type max_size() const { return nMaxSize; }
51     size_type max_size(size_type s)
52     {
53         if (s)
54             while (queue.size() > s)
55             {
56                 set.erase(queue.front());
57                 queue.pop_front();
58             }
59         nMaxSize = s;
60         return nMaxSize;
61     }
62 };
63
64 #endif