Back to home page

Bitcoin sources

 
 

    


File indexing completed on 2020-06-26 04:58:54

0001 // Copyright (c) 2012 The Bitcoin developers
0002 // Distributed under the MIT/X11 software license, see the accompanying
0003 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
0004 
0005 #ifndef BITCOIN_MRUSET_H
0006 #define BITCOIN_MRUSET_H
0007 
0008 #include <deque>
0009 #include <set>
0010 #include <utility>
0011 
0012 /** STL-like set container that only keeps the most recent N elements. */
0013 template <typename T>
0014 class mruset
0015 {
0016 public:
0017     typedef T key_type;
0018     typedef T value_type;
0019     typedef typename std::set<T>::iterator iterator;
0020     typedef typename std::set<T>::const_iterator const_iterator;
0021     typedef typename std::set<T>::size_type size_type;
0022 
0023 protected:
0024     std::set<T> set;
0025     std::deque<T> queue;
0026     size_type nMaxSize;
0027 
0028 public:
0029     mruset(size_type nMaxSizeIn = 0) { nMaxSize = nMaxSizeIn; }
0030     iterator begin() const { return set.begin(); }
0031     iterator end() const { return set.end(); }
0032     size_type size() const { return set.size(); }
0033     bool empty() const { return set.empty(); }
0034     iterator find(const key_type& k) const { return set.find(k); }
0035     size_type count(const key_type& k) const { return set.count(k); }
0036     void clear()
0037     {
0038         set.clear();
0039         queue.clear();
0040     }
0041     bool inline friend operator==(const mruset<T>& a, const mruset<T>& b) { return a.set == b.set; }
0042     bool inline friend operator==(const mruset<T>& a, const std::set<T>& b) { return a.set == b; }
0043     bool inline friend operator<(const mruset<T>& a, const mruset<T>& b) { return a.set < b.set; }
0044     std::pair<iterator, bool> insert(const key_type& x)
0045     {
0046         std::pair<iterator, bool> ret = set.insert(x);
0047         if (ret.second) {
0048             if (nMaxSize && queue.size() == nMaxSize) {
0049                 set.erase(queue.front());
0050                 queue.pop_front();
0051             }
0052             queue.push_back(x);
0053         }
0054         return ret;
0055     }
0056     size_type max_size() const { return nMaxSize; }
0057     size_type max_size(size_type s)
0058     {
0059         if (s)
0060             while (queue.size() > s) {
0061                 set.erase(queue.front());
0062                 queue.pop_front();
0063             }
0064         nMaxSize = s;
0065         return nMaxSize;
0066     }
0067 };
0068 
0069 #endif // BITCOIN_MRUSET_H