PIVX Core  5.6.99
P2P Digital Currency
cyclingvector.h
Go to the documentation of this file.
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>
19 {
20 private:
21  mutable RecursiveMutex cs;
22  unsigned int MAX_SIZE;
23  std::vector<T> vec;
24 
25 public:
26  CyclingVector(unsigned int _MAX_SIZE, const T& defaultVal):
27  MAX_SIZE(_MAX_SIZE),
28  vec(_MAX_SIZE, defaultVal)
29  {}
30 
31  T Get(int idx) const { LOCK(cs); return vec[idx % MAX_SIZE]; }
32  void Set(int idx, const T& value) { LOCK(cs); vec[idx % MAX_SIZE] = value; }
33  std::vector<T> GetCache() const { LOCK(cs); return vec; }
34 };
35 
36 #endif // PIVX_CYCLINGVECTOR_H
std::vector< T > vec
Definition: cyclingvector.h:23
T Get(int idx) const
Definition: cyclingvector.h:31
std::vector< T > GetCache() const
Definition: cyclingvector.h:33
RecursiveMutex cs
Definition: cyclingvector.h:21
unsigned int MAX_SIZE
Definition: cyclingvector.h:22
void Set(int idx, const T &value)
Definition: cyclingvector.h:32
CyclingVector(unsigned int _MAX_SIZE, const T &defaultVal)
Definition: cyclingvector.h:26
#define T(expected, seed, data)
@ LOCK
Definition: lockunlock.h:16