Skip to content

Commit ddf63fe

Browse files
committed
[Refactor] Introduce CyclingVector class
1 parent 2c60025 commit ddf63fe

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/Makefile.am

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ BITCOIN_CORE_H = \
179179
core_io.h \
180180
cuckoocache.h \
181181
crypter.h \
182+
cyclingvector.h \
182183
pairresult.h \
183184
addressbook.h \
184185
denomination_functions.h \

src/cyclingvector.h

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Copyright (c) 2020 The PIVX 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+
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

0 commit comments

Comments
 (0)