CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/Common/Data/Collections/CyclicBuffer.h
Views: 1401
1
// Copyright (c) 2024- PPSSPP Project.
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official git repository and contact information can be found at
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18
#pragma once
19
20
#include <vector>
21
22
#include "Common/CommonTypes.h"
23
24
25
template <typename T>
26
struct CyclicBuffer {
27
std::vector<T> buffer;
28
u32 current_index;
29
bool overflow;
30
31
explicit CyclicBuffer(u32 capacity) : buffer(capacity, T()), current_index(0), overflow(false) {}
32
33
CyclicBuffer(): buffer(), current_index(0), overflow(false) {}
34
35
void push_back(const T& value);
36
void push_back(T&& value);
37
38
void clear();
39
void resize(u32 new_capacity);
40
41
std::vector<T> get_content() const;
42
};
43
44
template<typename T>
45
std::vector<T> CyclicBuffer<T>::get_content() const {
46
if (!overflow) {
47
return std::vector<T>(buffer.begin(), buffer.begin() + current_index);
48
}
49
50
std::vector<T> ans;
51
ans.reserve(buffer.size());
52
std::copy(buffer.begin() + current_index, buffer.end(), std::back_inserter(ans));
53
std::copy(buffer.begin(), buffer.begin() + current_index, std::back_inserter(ans));
54
return ans;
55
}
56
57
template <typename T>
58
void CyclicBuffer<T>::push_back(const T& value) {
59
buffer[current_index] = value;
60
++current_index;
61
if (current_index == buffer.size()) {
62
current_index = 0;
63
overflow = true;
64
}
65
}
66
67
template <typename T>
68
void CyclicBuffer<T>::push_back(T&& value) {
69
buffer[current_index] = std::move(value);
70
++current_index;
71
if (current_index == buffer.size()) {
72
current_index = 0;
73
overflow = true;
74
}
75
}
76
77
template <typename T>
78
void CyclicBuffer<T>::clear() {
79
buffer.clear();
80
current_index = 0;
81
overflow = false;
82
}
83
84
template <typename T>
85
void CyclicBuffer<T>::resize(u32 new_capacity) {
86
buffer.resize(new_capacity);
87
}
88
89