Line data Source code
1 : // Copyright (c) 2020 The PIVX Core developers 2 : // Distributed under the MIT software license, see the accompanying 3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 : 5 : #ifndef PIVX_CYCLINGVECTOR_H 6 : #define PIVX_CYCLINGVECTOR_H 7 : 8 : #include <sync.h> 9 : #include <vector> 10 : 11 : /* 12 : * Vector container that keeps only MAX_SIZE elements. 13 : * Initialized with empty objects. 14 : * Exposes only atomic getter and setter 15 : * (which cycles the vector index modulo MAX_SIZE) 16 : */ 17 : template <typename T> 18 : class CyclingVector 19 : { 20 : private: 21 : mutable RecursiveMutex cs; 22 : unsigned int MAX_SIZE; 23 : std::vector<T> vec; 24 : 25 : public: 26 479 : CyclingVector(unsigned int _MAX_SIZE, const T& defaultVal): 27 : MAX_SIZE(_MAX_SIZE), 28 479 : vec(_MAX_SIZE, defaultVal) 29 : {} 30 : 31 98419 : T Get(int idx) const { LOCK(cs); return vec[idx % MAX_SIZE]; } 32 66257 : void Set(int idx, const T& value) { LOCK(cs); vec[idx % MAX_SIZE] = value; } 33 12 : std::vector<T> GetCache() const { LOCK(cs); return vec; } 34 : }; 35 : 36 : #endif // PIVX_CYCLINGVECTOR_H