]> Git Repo - VerusCoin.git/blame - src/mruset.h
Make some global variables less-global (static)
[VerusCoin.git] / src / mruset.h
CommitLineData
d4d5022c 1// Copyright (c) 2012-2015 The Bitcoin Core developers
78253fcb 2// Distributed under the MIT software license, see the accompanying
3a25a2b9 3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
51ed9ec9 4
c4341fa6
PW
5#ifndef BITCOIN_MRUSET_H
6#define BITCOIN_MRUSET_H
7
51ed9ec9 8#include <set>
d4d5022c 9#include <vector>
51ed9ec9 10#include <utility>
c4341fa6 11
6b8de05d 12/** STL-like set container that only keeps the most recent N elements. */
20e01b1a
PW
13template <typename T>
14class mruset
c4341fa6
PW
15{
16public:
17 typedef T key_type;
18 typedef T value_type;
19 typedef typename std::set<T>::iterator iterator;
20 typedef typename std::set<T>::const_iterator const_iterator;
21 typedef typename std::set<T>::size_type size_type;
22
23protected:
24 std::set<T> set;
d4d5022c
PW
25 std::vector<iterator> order;
26 size_type first_used;
27 size_type first_unused;
28 const size_type nMaxSize;
c4341fa6
PW
29
30public:
d4d5022c 31 mruset(size_type nMaxSizeIn = 1) : nMaxSize(nMaxSizeIn) { clear(); }
c4341fa6
PW
32 iterator begin() const { return set.begin(); }
33 iterator end() const { return set.end(); }
34 size_type size() const { return set.size(); }
35 bool empty() const { return set.empty(); }
36 iterator find(const key_type& k) const { return set.find(k); }
37 size_type count(const key_type& k) const { return set.count(k); }
20e01b1a
PW
38 void clear()
39 {
40 set.clear();
d4d5022c
PW
41 order.assign(nMaxSize, set.end());
42 first_used = 0;
43 first_unused = 0;
20e01b1a 44 }
c4341fa6
PW
45 bool inline friend operator==(const mruset<T>& a, const mruset<T>& b) { return a.set == b.set; }
46 bool inline friend operator==(const mruset<T>& a, const std::set<T>& b) { return a.set == b; }
47 bool inline friend operator<(const mruset<T>& a, const mruset<T>& b) { return a.set < b.set; }
48 std::pair<iterator, bool> insert(const key_type& x)
49 {
50 std::pair<iterator, bool> ret = set.insert(x);
20e01b1a 51 if (ret.second) {
d4d5022c
PW
52 if (set.size() == nMaxSize + 1) {
53 set.erase(order[first_used]);
54 order[first_used] = set.end();
55 if (++first_used == nMaxSize) first_used = 0;
c4341fa6 56 }
d4d5022c
PW
57 order[first_unused] = ret.first;
58 if (++first_unused == nMaxSize) first_unused = 0;
c4341fa6
PW
59 }
60 return ret;
61 }
62 size_type max_size() const { return nMaxSize; }
c4341fa6
PW
63};
64
093303a8 65#endif // BITCOIN_MRUSET_H
This page took 0.182545 seconds and 4 git commands to generate.