2014-12-17 02:47:57 +01:00
|
|
|
// Copyright (c) 2012 The Bitcoin Core developers
|
2014-12-13 05:09:33 +01:00
|
|
|
// Distributed under the MIT software license, see the accompanying
|
2012-05-18 16:02:28 +02:00
|
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
2013-04-13 07:13:08 +02:00
|
|
|
|
2012-02-27 17:55:53 +01:00
|
|
|
#ifndef BITCOIN_MRUSET_H
|
|
|
|
#define BITCOIN_MRUSET_H
|
|
|
|
|
|
|
|
#include <deque>
|
2013-04-13 07:13:08 +02:00
|
|
|
#include <set>
|
|
|
|
#include <utility>
|
2012-02-27 17:55:53 +01:00
|
|
|
|
2012-03-26 16:48:23 +02:00
|
|
|
/** STL-like set container that only keeps the most recent N elements. */
|
2014-09-19 19:21:46 +02:00
|
|
|
template <typename T>
|
|
|
|
class mruset
|
2012-02-27 17:55:53 +01:00
|
|
|
{
|
|
|
|
public:
|
|
|
|
typedef T key_type;
|
|
|
|
typedef T value_type;
|
|
|
|
typedef typename std::set<T>::iterator iterator;
|
|
|
|
typedef typename std::set<T>::const_iterator const_iterator;
|
|
|
|
typedef typename std::set<T>::size_type size_type;
|
|
|
|
|
|
|
|
protected:
|
|
|
|
std::set<T> set;
|
|
|
|
std::deque<T> queue;
|
|
|
|
size_type nMaxSize;
|
|
|
|
|
|
|
|
public:
|
|
|
|
mruset(size_type nMaxSizeIn = 0) { nMaxSize = nMaxSizeIn; }
|
|
|
|
iterator begin() const { return set.begin(); }
|
|
|
|
iterator end() const { return set.end(); }
|
|
|
|
size_type size() const { return set.size(); }
|
|
|
|
bool empty() const { return set.empty(); }
|
|
|
|
iterator find(const key_type& k) const { return set.find(k); }
|
|
|
|
size_type count(const key_type& k) const { return set.count(k); }
|
2014-09-19 19:21:46 +02:00
|
|
|
void clear()
|
|
|
|
{
|
|
|
|
set.clear();
|
|
|
|
queue.clear();
|
|
|
|
}
|
2012-02-27 17:55:53 +01:00
|
|
|
bool inline friend operator==(const mruset<T>& a, const mruset<T>& b) { return a.set == b.set; }
|
|
|
|
bool inline friend operator==(const mruset<T>& a, const std::set<T>& b) { return a.set == b; }
|
|
|
|
bool inline friend operator<(const mruset<T>& a, const mruset<T>& b) { return a.set < b.set; }
|
|
|
|
std::pair<iterator, bool> insert(const key_type& x)
|
|
|
|
{
|
|
|
|
std::pair<iterator, bool> ret = set.insert(x);
|
2014-09-19 19:21:46 +02:00
|
|
|
if (ret.second) {
|
|
|
|
if (nMaxSize && queue.size() == nMaxSize) {
|
2012-02-27 17:55:53 +01:00
|
|
|
set.erase(queue.front());
|
|
|
|
queue.pop_front();
|
|
|
|
}
|
|
|
|
queue.push_back(x);
|
|
|
|
}
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
size_type max_size() const { return nMaxSize; }
|
|
|
|
size_type max_size(size_type s)
|
|
|
|
{
|
|
|
|
if (s)
|
2014-09-19 19:21:46 +02:00
|
|
|
while (queue.size() > s) {
|
2012-02-27 17:55:53 +01:00
|
|
|
set.erase(queue.front());
|
|
|
|
queue.pop_front();
|
|
|
|
}
|
|
|
|
nMaxSize = s;
|
|
|
|
return nMaxSize;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-08-28 22:21:03 +02:00
|
|
|
#endif // BITCOIN_MRUSET_H
|