RingBuffer.hpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_RINGBUFFER_H
  14. #define ZT_RINGBUFFER_H
  15. #include <typeinfo>
  16. #include <cstdint>
  17. #include <stdlib.h>
  18. #include <memory.h>
  19. #include <algorithm>
  20. #include <math.h>
  21. namespace ZeroTier {
  22. /**
  23. * A circular buffer
  24. *
  25. * For fast handling of continuously-evolving variables (such as path quality metrics).
  26. * Using this, we can maintain longer sliding historical windows for important path
  27. * metrics without the need for potentially expensive calls to memcpy/memmove.
  28. *
  29. * Some basic statistical functionality is implemented here in an attempt
  30. * to reduce the complexity of code needed to interact with this type of buffer.
  31. */
  32. template <class T,size_t S>
  33. class RingBuffer
  34. {
  35. private:
  36. T buf[S];
  37. size_t begin;
  38. size_t end;
  39. bool wrap;
  40. public:
  41. RingBuffer() :
  42. begin(0),
  43. end(0),
  44. wrap(false)
  45. {
  46. memset(buf,0,sizeof(T)*S);
  47. }
  48. /**
  49. * @return A pointer to the underlying buffer
  50. */
  51. inline T *get_buf()
  52. {
  53. return buf + begin;
  54. }
  55. /**
  56. * Adjust buffer index pointer as if we copied data in
  57. * @param n Number of elements to copy in
  58. * @return Number of elements we copied in
  59. */
  60. inline size_t produce(size_t n)
  61. {
  62. n = std::min(n, getFree());
  63. if (n == 0) {
  64. return n;
  65. }
  66. const size_t first_chunk = std::min(n, S - end);
  67. end = (end + first_chunk) % S;
  68. if (first_chunk < n) {
  69. const size_t second_chunk = n - first_chunk;
  70. end = (end + second_chunk) % S;
  71. }
  72. if (begin == end) {
  73. wrap = true;
  74. }
  75. return n;
  76. }
  77. /**
  78. * Fast erase, O(1).
  79. * Merely reset the buffer pointer, doesn't erase contents
  80. */
  81. inline void reset() { consume(count()); }
  82. /**
  83. * adjust buffer index pointer as if we copied data out
  84. * @param n Number of elements we copied from the buffer
  85. * @return Number of elements actually available from the buffer
  86. */
  87. inline size_t consume(size_t n)
  88. {
  89. n = std::min(n, count());
  90. if (n == 0) {
  91. return n;
  92. }
  93. if (wrap) {
  94. wrap = false;
  95. }
  96. const size_t first_chunk = std::min(n, S - begin);
  97. begin = (begin + first_chunk) % S;
  98. if (first_chunk < n) {
  99. const size_t second_chunk = n - first_chunk;
  100. begin = (begin + second_chunk) % S;
  101. }
  102. return n;
  103. }
  104. /**
  105. * @param data Buffer that is to be written to the ring
  106. * @param n Number of elements to write to the buffer
  107. */
  108. inline size_t write(const T * data, size_t n)
  109. {
  110. n = std::min(n, getFree());
  111. if (n == 0) {
  112. return n;
  113. }
  114. const size_t first_chunk = std::min(n, S - end);
  115. memcpy(buf + end, data, first_chunk * sizeof(T));
  116. end = (end + first_chunk) % S;
  117. if (first_chunk < n) {
  118. const size_t second_chunk = n - first_chunk;
  119. memcpy(buf + end, data + first_chunk, second_chunk * sizeof(T));
  120. end = (end + second_chunk) % S;
  121. }
  122. if (begin == end) {
  123. wrap = true;
  124. }
  125. return n;
  126. }
  127. /**
  128. * Place a single value on the buffer. If the buffer is full, consume a value first.
  129. *
  130. * @param value A single value to be placed in the buffer
  131. */
  132. inline void push(const T value)
  133. {
  134. if (count() == S) {
  135. consume(1);
  136. }
  137. const size_t first_chunk = std::min((size_t)1, S - end);
  138. *(buf + end) = value;
  139. end = (end + first_chunk) % S;
  140. if (begin == end) {
  141. wrap = true;
  142. }
  143. }
  144. /**
  145. * @return The most recently pushed element on the buffer
  146. */
  147. inline T get_most_recent() { return *(buf + end); }
  148. /**
  149. * @param dest Destination buffer
  150. * @param n Size (in terms of number of elements) of the destination buffer
  151. * @return Number of elements read from the buffer
  152. */
  153. inline size_t read(T *dest,size_t n)
  154. {
  155. n = std::min(n, count());
  156. if (n == 0) {
  157. return n;
  158. }
  159. if (wrap) {
  160. wrap = false;
  161. }
  162. const size_t first_chunk = std::min(n, S - begin);
  163. memcpy(dest, buf + begin, first_chunk * sizeof(T));
  164. begin = (begin + first_chunk) % S;
  165. if (first_chunk < n) {
  166. const size_t second_chunk = n - first_chunk;
  167. memcpy(dest + first_chunk, buf + begin, second_chunk * sizeof(T));
  168. begin = (begin + second_chunk) % S;
  169. }
  170. return n;
  171. }
  172. /**
  173. * Return how many elements are in the buffer, O(1).
  174. *
  175. * @return The number of elements in the buffer
  176. */
  177. inline size_t count()
  178. {
  179. if (end == begin) {
  180. return wrap ? S : 0;
  181. } else if (end > begin) {
  182. return end - begin;
  183. } else {
  184. return S + end - begin;
  185. }
  186. }
  187. /**
  188. * @return The number of slots that are unused in the buffer
  189. */
  190. inline size_t getFree() { return S - count(); }
  191. /**
  192. * @return The arithmetic mean of the contents of the buffer
  193. */
  194. inline float mean()
  195. {
  196. size_t iterator = begin;
  197. float subtotal = 0;
  198. size_t curr_cnt = count();
  199. for (size_t i=0; i<curr_cnt; i++) {
  200. iterator = (iterator + S - 1) % curr_cnt;
  201. subtotal += (float)*(buf + iterator);
  202. }
  203. return curr_cnt ? subtotal / (float)curr_cnt : 0;
  204. }
  205. /**
  206. * @return The arithmetic mean of the most recent 'n' elements of the buffer
  207. */
  208. inline float mean(size_t n)
  209. {
  210. n = n < S ? n : S;
  211. size_t iterator = begin;
  212. float subtotal = 0;
  213. size_t curr_cnt = count();
  214. for (size_t i=0; i<n; i++) {
  215. iterator = (iterator + S - 1) % curr_cnt;
  216. subtotal += (float)*(buf + iterator);
  217. }
  218. return curr_cnt ? subtotal / (float)curr_cnt : 0;
  219. }
  220. /**
  221. * @return The sum of the contents of the buffer
  222. */
  223. inline float sum()
  224. {
  225. size_t iterator = begin;
  226. float total = 0;
  227. size_t curr_cnt = count();
  228. for (size_t i=0; i<curr_cnt; i++) {
  229. iterator = (iterator + S - 1) % curr_cnt;
  230. total += (float)*(buf + iterator);
  231. }
  232. return total;
  233. }
  234. /**
  235. * @return The sample standard deviation of element values
  236. */
  237. inline float stddev() { return sqrt(variance()); }
  238. /**
  239. * @return The variance of element values
  240. */
  241. inline float variance()
  242. {
  243. size_t iterator = begin;
  244. float cached_mean = mean();
  245. size_t curr_cnt = count();
  246. T sum_of_squared_deviations = 0;
  247. for (size_t i=0; i<curr_cnt; i++) {
  248. iterator = (iterator + S - 1) % curr_cnt;
  249. float deviation = (buf[i] - cached_mean);
  250. sum_of_squared_deviations += (T)(deviation*deviation);
  251. }
  252. float variance = (float)sum_of_squared_deviations / (float)(S - 1);
  253. return variance;
  254. }
  255. /**
  256. * @return The number of elements of zero value
  257. */
  258. inline size_t zeroCount()
  259. {
  260. size_t iterator = begin;
  261. size_t zeros = 0;
  262. size_t curr_cnt = count();
  263. for (size_t i=0; i<curr_cnt; i++) {
  264. iterator = (iterator + S - 1) % curr_cnt;
  265. if (*(buf + iterator) == 0) {
  266. zeros++;
  267. }
  268. }
  269. return zeros;
  270. }
  271. /**
  272. * @param value Value to match against in buffer
  273. * @return The number of values held in the ring buffer which match a given value
  274. */
  275. inline size_t countValue(T value)
  276. {
  277. size_t iterator = begin;
  278. size_t cnt = 0;
  279. size_t curr_cnt = count();
  280. for (size_t i=0; i<curr_cnt; i++) {
  281. iterator = (iterator + S - 1) % curr_cnt;
  282. if (*(buf + iterator) == value) {
  283. cnt++;
  284. }
  285. }
  286. return cnt;
  287. }
  288. /**
  289. * Print the contents of the buffer
  290. */
  291. /*
  292. inline void dump()
  293. {
  294. size_t iterator = begin;
  295. for (size_t i=0; i<S; i++) {
  296. iterator = (iterator + S - 1) % S;
  297. if (typeid(T) == typeid(int)) {
  298. fprintf(stderr, "buf[%2zu]=%2d\n", iterator, (int)*(buf + iterator));
  299. }
  300. else {
  301. fprintf(stderr, "buf[%2zu]=%2f\n", iterator, (float)*(buf + iterator));
  302. }
  303. }
  304. }
  305. */
  306. };
  307. } // namespace ZeroTier
  308. #endif