RingBuffer.hpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_RINGBUFFER_H
  27. #define ZT_RINGBUFFER_H
  28. #include <typeinfo>
  29. #include <cstdint>
  30. #include <stdlib.h>
  31. #include <memory.h>
  32. #include <algorithm>
  33. #include <math.h>
  34. namespace ZeroTier {
  35. /**
  36. * A circular buffer
  37. *
  38. * For fast handling of continuously-evolving variables (such as path quality metrics).
  39. * Using this, we can maintain longer sliding historical windows for important path
  40. * metrics without the need for potentially expensive calls to memcpy/memmove.
  41. *
  42. * Some basic statistical functionality is implemented here in an attempt
  43. * to reduce the complexity of code needed to interact with this type of buffer.
  44. */
  45. template <class T>
  46. class RingBuffer
  47. {
  48. private:
  49. T * buf;
  50. size_t size;
  51. size_t begin;
  52. size_t end;
  53. bool wrap;
  54. public:
  55. /**
  56. * create a RingBuffer with space for up to size elements.
  57. */
  58. explicit RingBuffer(size_t size)
  59. : size(size),
  60. begin(0),
  61. end(0),
  62. wrap(false)
  63. {
  64. buf = new T[size];
  65. memset(buf, 0, sizeof(T) * size);
  66. }
  67. ~RingBuffer()
  68. {
  69. delete [] buf;
  70. }
  71. /**
  72. * @return A pointer to the underlying buffer
  73. */
  74. T* get_buf()
  75. {
  76. return buf + begin;
  77. }
  78. /**
  79. * Adjust buffer index pointer as if we copied data in
  80. * @param n Number of elements to copy in
  81. * @return Number of elements we copied in
  82. */
  83. size_t produce(size_t n)
  84. {
  85. n = std::min(n, getFree());
  86. if (n == 0) {
  87. return n;
  88. }
  89. const size_t first_chunk = std::min(n, size - end);
  90. end = (end + first_chunk) % size;
  91. if (first_chunk < n) {
  92. const size_t second_chunk = n - first_chunk;
  93. end = (end + second_chunk) % size;
  94. }
  95. if (begin == end) {
  96. wrap = true;
  97. }
  98. return n;
  99. }
  100. /**
  101. * Fast erase, O(1).
  102. * Merely reset the buffer pointer, doesn't erase contents
  103. */
  104. void reset()
  105. {
  106. consume(count());
  107. }
  108. /**
  109. * adjust buffer index pointer as if we copied data out
  110. * @param n Number of elements we copied from the buffer
  111. * @return Number of elements actually available from the buffer
  112. */
  113. size_t consume(size_t n)
  114. {
  115. n = std::min(n, count());
  116. if (n == 0) {
  117. return n;
  118. }
  119. if (wrap) {
  120. wrap = false;
  121. }
  122. const size_t first_chunk = std::min(n, size - begin);
  123. begin = (begin + first_chunk) % size;
  124. if (first_chunk < n) {
  125. const size_t second_chunk = n - first_chunk;
  126. begin = (begin + second_chunk) % size;
  127. }
  128. return n;
  129. }
  130. /**
  131. * @param data Buffer that is to be written to the ring
  132. * @param n Number of elements to write to the buffer
  133. */
  134. size_t write(const T * data, size_t n)
  135. {
  136. n = std::min(n, getFree());
  137. if (n == 0) {
  138. return n;
  139. }
  140. const size_t first_chunk = std::min(n, size - end);
  141. memcpy(buf + end, data, first_chunk * sizeof(T));
  142. end = (end + first_chunk) % size;
  143. if (first_chunk < n) {
  144. const size_t second_chunk = n - first_chunk;
  145. memcpy(buf + end, data + first_chunk, second_chunk * sizeof(T));
  146. end = (end + second_chunk) % size;
  147. }
  148. if (begin == end) {
  149. wrap = true;
  150. }
  151. return n;
  152. }
  153. /**
  154. * Place a single value on the buffer. If the buffer is full, consume a value first.
  155. *
  156. * @param value A single value to be placed in the buffer
  157. */
  158. void push(const T value)
  159. {
  160. if (count() == size) {
  161. consume(1);
  162. }
  163. const size_t first_chunk = std::min((size_t)1, size - end);
  164. *(buf + end) = value;
  165. end = (end + first_chunk) % size;
  166. if (begin == end) {
  167. wrap = true;
  168. }
  169. }
  170. /**
  171. * @return The most recently pushed element on the buffer
  172. */
  173. T get_most_recent() { return *(buf + end); }
  174. /**
  175. * @param dest Destination buffer
  176. * @param n Size (in terms of number of elements) of the destination buffer
  177. * @return Number of elements read from the buffer
  178. */
  179. size_t read(T * dest, size_t n)
  180. {
  181. n = std::min(n, count());
  182. if (n == 0) {
  183. return n;
  184. }
  185. if (wrap) {
  186. wrap = false;
  187. }
  188. const size_t first_chunk = std::min(n, size - begin);
  189. memcpy(dest, buf + begin, first_chunk * sizeof(T));
  190. begin = (begin + first_chunk) % size;
  191. if (first_chunk < n) {
  192. const size_t second_chunk = n - first_chunk;
  193. memcpy(dest + first_chunk, buf + begin, second_chunk * sizeof(T));
  194. begin = (begin + second_chunk) % size;
  195. }
  196. return n;
  197. }
  198. /**
  199. * Return how many elements are in the buffer, O(1).
  200. *
  201. * @return The number of elements in the buffer
  202. */
  203. size_t count()
  204. {
  205. if (end == begin) {
  206. return wrap ? size : 0;
  207. }
  208. else if (end > begin) {
  209. return end - begin;
  210. }
  211. else {
  212. return size + end - begin;
  213. }
  214. }
  215. /**
  216. * @return The number of slots that are unused in the buffer
  217. */
  218. size_t getFree() { return size - count(); }
  219. /**
  220. * @return The arithmetic mean of the contents of the buffer
  221. */
  222. float mean()
  223. {
  224. size_t iterator = begin;
  225. float subtotal = 0;
  226. size_t curr_cnt = count();
  227. for (size_t i=0; i<curr_cnt; i++) {
  228. iterator = (iterator + size - 1) % curr_cnt;
  229. subtotal += (float)*(buf + iterator);
  230. }
  231. return curr_cnt ? subtotal / (float)curr_cnt : 0;
  232. }
  233. /**
  234. * @return The arithmetic mean of the most recent 'n' elements of the buffer
  235. */
  236. float mean(size_t n)
  237. {
  238. n = n < size ? n : size;
  239. size_t iterator = begin;
  240. float subtotal = 0;
  241. size_t curr_cnt = count();
  242. for (size_t i=0; i<n; i++) {
  243. iterator = (iterator + size - 1) % curr_cnt;
  244. subtotal += (float)*(buf + iterator);
  245. }
  246. return curr_cnt ? subtotal / (float)curr_cnt : 0;
  247. }
  248. /**
  249. * @return The sample standard deviation of element values
  250. */
  251. float stddev() { return sqrt(variance()); }
  252. /**
  253. * @return The variance of element values
  254. */
  255. float variance()
  256. {
  257. size_t iterator = begin;
  258. float cached_mean = mean();
  259. size_t curr_cnt = count();
  260. if (size) {
  261. T sum_of_squared_deviations = 0;
  262. for (size_t i=0; i<curr_cnt; i++) {
  263. iterator = (iterator + size - 1) % curr_cnt;
  264. float deviation = (buf[i] - cached_mean);
  265. sum_of_squared_deviations += (deviation*deviation);
  266. }
  267. float variance = (float)sum_of_squared_deviations / (float)(size - 1);
  268. return variance;
  269. }
  270. return 0;
  271. }
  272. /**
  273. * @return The number of elements of zero value
  274. */
  275. size_t zeroCount()
  276. {
  277. size_t iterator = begin;
  278. size_t zeros = 0;
  279. size_t curr_cnt = count();
  280. for (size_t i=0; i<curr_cnt; i++) {
  281. iterator = (iterator + size - 1) % curr_cnt;
  282. if (*(buf + iterator) == 0) {
  283. zeros++;
  284. }
  285. }
  286. return zeros;
  287. }
  288. /**
  289. * @param value Value to match against in buffer
  290. * @return The number of values held in the ring buffer which match a given value
  291. */
  292. size_t countValue(T value)
  293. {
  294. size_t iterator = begin;
  295. size_t cnt = 0;
  296. size_t curr_cnt = count();
  297. for (size_t i=0; i<curr_cnt; i++) {
  298. iterator = (iterator + size - 1) % curr_cnt;
  299. if (*(buf + iterator) == value) {
  300. cnt++;
  301. }
  302. }
  303. return cnt;
  304. }
  305. /**
  306. * Print the contents of the buffer
  307. */
  308. void dump()
  309. {
  310. size_t iterator = begin;
  311. for (size_t i=0; i<size; i++) {
  312. iterator = (iterator + size - 1) % size;
  313. if (typeid(T) == typeid(int)) {
  314. //DEBUG_INFO("buf[%2zu]=%2d", iterator, (int)*(buf + iterator));
  315. }
  316. else {
  317. //DEBUG_INFO("buf[%2zu]=%2f", iterator, (float)*(buf + iterator));
  318. }
  319. }
  320. }
  321. };
  322. } // namespace ZeroTier
  323. #endif