summaryrefslogtreecommitdiff
path: root/node/RingBuffer.hpp
blob: 0f29a89a95b6816728534605ecf36c4483b318f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/*
 * ZeroTier One - Network Virtualization Everywhere
 * Copyright (C) 2011-2019  ZeroTier, Inc.  https://www.zerotier.com/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * --
 *
 * You can be released from the requirements of the license by purchasing
 * a commercial license. Buying such a license is mandatory as soon as you
 * develop commercial closed-source software that incorporates or links
 * directly against ZeroTier software without disclosing the source code
 * of your own application.
 */

#ifndef ZT_RINGBUFFER_H
#define ZT_RINGBUFFER_H

#include <typeinfo>
#include <cstdint>
#include <stdlib.h>
#include <memory.h>
#include <algorithm>
#include <math.h>

namespace ZeroTier {

/**
 * A circular buffer
 *
 * For fast handling of continuously-evolving variables (such as path quality metrics).
 * Using this, we can maintain longer sliding historical windows for important path 
 * metrics without the need for potentially expensive calls to memcpy/memmove.
 *
 * Some basic statistical functionality is implemented here in an attempt
 * to reduce the complexity of code needed to interact with this type of buffer.
 */

template <class T,size_t S>
class RingBuffer
{
private:
	T buf[S];
	size_t begin;
	size_t end;
	bool wrap;

public:
	RingBuffer() :
		begin(0),
		end(0),
		wrap(false)
	{
		memset(buf,0,sizeof(T)*S);
	}

	/**
	 * @return A pointer to the underlying buffer
	 */
	inline T *get_buf()
	{
		return buf + begin;
	}

	/** 
	 * Adjust buffer index pointer as if we copied data in
	 * @param n Number of elements to copy in
	 * @return Number of elements we copied in
	 */
	inline size_t produce(size_t n)
	{
		n = std::min(n, getFree());
		if (n == 0) {
			return n;
		}
		const size_t first_chunk = std::min(n, S - end);
		end = (end + first_chunk) % S;
		if (first_chunk < n) {
			const size_t second_chunk = n - first_chunk;
			end = (end + second_chunk) % S;
		}
		if (begin == end) {
			wrap = true;
		}
		return n;
	}

	/** 
	 * Fast erase, O(1). 
	 * Merely reset the buffer pointer, doesn't erase contents
	 */
	inline void reset() { consume(count()); }

	/** 
	 * adjust buffer index pointer as if we copied data out
	 * @param n Number of elements we copied from the buffer
	 * @return Number of elements actually available from the buffer
	 */
	inline size_t consume(size_t n)
	{
		n = std::min(n, count());
		if (n == 0) {
			return n;
		}
		if (wrap) {
			wrap = false;
		}
		const size_t first_chunk = std::min(n, S - begin);
		begin = (begin + first_chunk) % S;
		if (first_chunk < n) {
			const size_t second_chunk = n - first_chunk;
			begin = (begin + second_chunk) % S;
		}
		return n;
	}

	/**
	 * @param data Buffer that is to be written to the ring
	 * @param n Number of elements to write to the buffer
	 */
	inline size_t write(const T * data, size_t n)
	{
		n = std::min(n, getFree());
		if (n == 0) {
			return n;
		}
		const size_t first_chunk = std::min(n, S - end);
		memcpy(buf + end, data, first_chunk * sizeof(T));
		end = (end + first_chunk) % S;
		if (first_chunk < n) {
			const size_t second_chunk = n - first_chunk;
			memcpy(buf + end, data + first_chunk, second_chunk * sizeof(T));
			end = (end + second_chunk) % S;
		}
		if (begin == end) {
			wrap = true;
		}
		return n;
	}

	/**
	 * Place a single value on the buffer. If the buffer is full, consume a value first.
	 *
	 * @param value A single value to be placed in the buffer
	 */
	inline void push(const T value)
	{
		if (count() == S) {
			consume(1);
		}
		const size_t first_chunk = std::min((size_t)1, S - end);
		*(buf + end) = value;
		end = (end + first_chunk) % S;
		if (begin == end) {
			wrap = true;
		}
	}

	/**
	 * @return The most recently pushed element on the buffer
	 */
	inline T get_most_recent() { return *(buf + end); }

	/**
	 * @param dest Destination buffer
	 * @param n Size (in terms of number of elements) of the destination buffer
	 * @return Number of elements read from the buffer
	 */
	inline size_t read(T *dest,size_t n)
	{
		n = std::min(n, count());
		if (n == 0) {
			return n;
		}
		if (wrap) {
			wrap = false;
		}
		const size_t first_chunk = std::min(n, S - begin);
		memcpy(dest, buf + begin, first_chunk * sizeof(T));
		begin = (begin + first_chunk) % S;
		if (first_chunk < n) {
			const size_t second_chunk = n - first_chunk;
			memcpy(dest + first_chunk, buf + begin, second_chunk * sizeof(T));
			begin = (begin + second_chunk) % S;
		}
		return n;
	}

	/**
	 * Return how many elements are in the buffer, O(1).
	 *
	 * @return The number of elements in the buffer
	 */
	inline size_t count()
	{
		if (end == begin) {
			return wrap ? S : 0;
		}
		else if (end > begin) {
			return end - begin;
		}
		else {
			return S + end - begin;
		}
	}

	/**
	 * @return The number of slots that are unused in the buffer
	 */
	inline size_t getFree() { return S - count(); }

	/**
	 * @return The arithmetic mean of the contents of the buffer
	 */
	inline float mean()
	{
		size_t iterator = begin;
		float subtotal = 0;
		size_t curr_cnt = count();
		for (size_t i=0; i<curr_cnt; i++) {
			iterator = (iterator + S - 1) % curr_cnt;
			subtotal += (float)*(buf + iterator);
		}
		return curr_cnt ? subtotal / (float)curr_cnt : 0;
	}

	/**
	 * @return The arithmetic mean of the most recent 'n' elements of the buffer
	 */
	inline float mean(size_t n)
	{
		n = n < S ? n : S;
		size_t iterator = begin;
		float subtotal = 0;
		size_t curr_cnt = count();
		for (size_t i=0; i<n; i++) {
			iterator = (iterator + S - 1) % curr_cnt;
			subtotal += (float)*(buf + iterator);
		}
		return curr_cnt ? subtotal / (float)curr_cnt : 0;
	}

	/**
	 * @return The sample standard deviation of element values
	 */
	inline float stddev() { return sqrt(variance()); }

	/**
	 * @return The variance of element values
	 */
	inline float variance()
	{
		size_t iterator = begin;
		float cached_mean = mean();
		size_t curr_cnt = count();
		T sum_of_squared_deviations = 0;
		for (size_t i=0; i<curr_cnt; i++) {
			iterator = (iterator + S - 1) % curr_cnt;
			float deviation = (buf[i] - cached_mean);
			sum_of_squared_deviations += (T)(deviation*deviation);
		}
		float variance = (float)sum_of_squared_deviations / (float)(S - 1);
		return variance;
	}

	/**
	 * @return The number of elements of zero value
	 */
	inline size_t zeroCount()
	{
		size_t iterator = begin;
		size_t zeros = 0;
		size_t curr_cnt = count();
		for (size_t i=0; i<curr_cnt; i++) {
			iterator = (iterator + S - 1) % curr_cnt;
			if (*(buf + iterator) == 0) {
				zeros++;
			}
		}
		return zeros;
	}

	/**
	 * @param value Value to match against in buffer
	 * @return The number of values held in the ring buffer which match a given value
	 */
	inline size_t countValue(T value)
	{
		size_t iterator = begin;
		size_t cnt = 0;
		size_t curr_cnt = count();
		for (size_t i=0; i<curr_cnt; i++) {
			iterator = (iterator + S - 1) % curr_cnt;
			if (*(buf + iterator) == value) {
				cnt++;
			}
		}
		return cnt;
	}

	/**
	 * Print the contents of the buffer
	 */
	/*
	inline void dump()
	{
		size_t iterator = begin;
		for (size_t i=0; i<S; i++) {
			iterator = (iterator + S - 1) % S;
			if (typeid(T) == typeid(int)) {
				 //DEBUG_INFO("buf[%2zu]=%2d", iterator, (int)*(buf + iterator));
			}
			else {
				 //DEBUG_INFO("buf[%2zu]=%2f", iterator, (float)*(buf + iterator));
			}
		}
	}
	*/
};

} // namespace ZeroTier

#endif