1
- // Copyright (c) 2012 The Bitcoin Core developers
1
+ // Copyright (c) 2012-2015 The Bitcoin Core developers
2
2
// Distributed under the MIT software license, see the accompanying
3
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
4
5
5
#ifndef BITCOIN_MRUSET_H
6
6
#define BITCOIN_MRUSET_H
7
7
8
- #include < deque>
9
8
#include < set>
9
+ #include < vector>
10
10
#include < utility>
11
11
12
12
/* * STL-like set container that only keeps the most recent N elements. */
@@ -22,11 +22,13 @@ class mruset
22
22
23
23
protected:
24
24
std::set<T> set;
25
- std::deque<T> queue;
26
- size_type nMaxSize;
25
+ std::vector<iterator> order;
26
+ size_type first_used;
27
+ size_type first_unused;
28
+ const size_type nMaxSize;
27
29
28
30
public:
29
- mruset (size_type nMaxSizeIn = 0 ) { nMaxSize = nMaxSizeIn ; }
31
+ mruset (size_type nMaxSizeIn = 1 ) : nMaxSize(nMaxSizeIn) { clear () ; }
30
32
iterator begin () const { return set.begin (); }
31
33
iterator end () const { return set.end (); }
32
34
size_type size () const { return set.size (); }
@@ -36,7 +38,9 @@ class mruset
36
38
void clear ()
37
39
{
38
40
set.clear ();
39
- queue.clear ();
41
+ order.assign (nMaxSize, set.end ());
42
+ first_used = 0 ;
43
+ first_unused = 0 ;
40
44
}
41
45
bool inline friend operator ==(const mruset<T>& a, const mruset<T>& b) { return a.set == b.set ; }
42
46
bool inline friend operator ==(const mruset<T>& a, const std::set<T>& b) { return a.set == b; }
@@ -45,25 +49,17 @@ class mruset
45
49
{
46
50
std::pair<iterator, bool > ret = set.insert (x);
47
51
if (ret.second ) {
48
- if (nMaxSize && queue.size () == nMaxSize) {
49
- set.erase (queue.front ());
50
- queue.pop_front ();
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 ;
51
56
}
52
- queue.push_back (x);
57
+ order[first_unused] = ret.first ;
58
+ if (++first_unused == nMaxSize) first_unused = 0 ;
53
59
}
54
60
return ret;
55
61
}
56
62
size_type max_size () const { return nMaxSize; }
57
- size_type max_size (size_type s)
58
- {
59
- if (s)
60
- while (queue.size () > s) {
61
- set.erase (queue.front ());
62
- queue.pop_front ();
63
- }
64
- nMaxSize = s;
65
- return nMaxSize;
66
- }
67
63
};
68
64
69
65
#endif // BITCOIN_MRUSET_H
0 commit comments