RingBuffer.hpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 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. /**
  68. * @return A pointer to the underlying buffer
  69. */
  70. T* get_buf()
  71. {
  72. return buf + begin;
  73. }
  74. /**
  75. * Adjust buffer index pointer as if we copied data in
  76. * @param n Number of elements to copy in
  77. * @return Number of elements we copied in
  78. */
  79. size_t produce(size_t n)
  80. {
  81. n = std::min(n, getFree());
  82. if (n == 0) {
  83. return n;
  84. }
  85. const size_t first_chunk = std::min(n, size - end);
  86. end = (end + first_chunk) % size;
  87. if (first_chunk < n) {
  88. const size_t second_chunk = n - first_chunk;
  89. end = (end + second_chunk) % size;
  90. }
  91. if (begin == end) {
  92. wrap = true;
  93. }
  94. return n;
  95. }
  96. /**
  97. * Fast erase, O(1).
  98. * Merely reset the buffer pointer, doesn't erase contents
  99. */
  100. void reset()
  101. {
  102. consume(count());
  103. }
  104. /**
  105. * adjust buffer index pointer as if we copied data out
  106. * @param n Number of elements we copied from the buffer
  107. * @return Number of elements actually available from the buffer
  108. */
  109. size_t consume(size_t n)
  110. {
  111. n = std::min(n, count());
  112. if (n == 0) {
  113. return n;
  114. }
  115. if (wrap) {
  116. wrap = false;
  117. }
  118. const size_t first_chunk = std::min(n, size - begin);
  119. begin = (begin + first_chunk) % size;
  120. if (first_chunk < n) {
  121. const size_t second_chunk = n - first_chunk;
  122. begin = (begin + second_chunk) % size;
  123. }
  124. return n;
  125. }
  126. /**
  127. * @param data Buffer that is to be written to the ring
  128. * @param n Number of elements to write to the buffer
  129. */
  130. size_t write(const T * data, size_t n)
  131. {
  132. n = std::min(n, getFree());
  133. if (n == 0) {
  134. return n;
  135. }
  136. const size_t first_chunk = std::min(n, size - end);
  137. memcpy(buf + end, data, first_chunk * sizeof(T));
  138. end = (end + first_chunk) % size;
  139. if (first_chunk < n) {
  140. const size_t second_chunk = n - first_chunk;
  141. memcpy(buf + end, data + first_chunk, second_chunk * sizeof(T));
  142. end = (end + second_chunk) % size;
  143. }
  144. if (begin == end) {
  145. wrap = true;
  146. }
  147. return n;
  148. }
  149. /**
  150. * Place a single value on the buffer. If the buffer is full, consume a value first.
  151. *
  152. * @param value A single value to be placed in the buffer
  153. */
  154. void push(const T value)
  155. {
  156. if (count() == size) {
  157. consume(1);
  158. }
  159. const size_t first_chunk = std::min((size_t)1, size - end);
  160. *(buf + end) = value;
  161. end = (end + first_chunk) % size;
  162. if (begin == end) {
  163. wrap = true;
  164. }
  165. }
  166. /**
  167. * @return The most recently pushed element on the buffer
  168. */
  169. T get_most_recent() { return *(buf + end); }
  170. /**
  171. * @param dest Destination buffer
  172. * @param n Size (in terms of number of elements) of the destination buffer
  173. * @return Number of elements read from the buffer
  174. */
  175. size_t read(T * dest, size_t n)
  176. {
  177. n = std::min(n, count());
  178. if (n == 0) {
  179. return n;
  180. }
  181. if (wrap) {
  182. wrap = false;
  183. }
  184. const size_t first_chunk = std::min(n, size - begin);
  185. memcpy(dest, buf + begin, first_chunk * sizeof(T));
  186. begin = (begin + first_chunk) % size;
  187. if (first_chunk < n) {
  188. const size_t second_chunk = n - first_chunk;
  189. memcpy(dest + first_chunk, buf + begin, second_chunk * sizeof(T));
  190. begin = (begin + second_chunk) % size;
  191. }
  192. return n;
  193. }
  194. /**
  195. * Return how many elements are in the buffer, O(1).
  196. *
  197. * @return The number of elements in the buffer
  198. */
  199. size_t count()
  200. {
  201. if (end == begin) {
  202. return wrap ? size : 0;
  203. }
  204. else if (end > begin) {
  205. return end - begin;
  206. }
  207. else {
  208. return size + end - begin;
  209. }
  210. }
  211. /**
  212. * @return The number of slots that are unused in the buffer
  213. */
  214. size_t getFree() { return size - count(); }
  215. /**
  216. * @return The arithmetic mean of the contents of the buffer
  217. */
  218. float mean()
  219. {
  220. size_t iterator = begin;
  221. float subtotal = 0;
  222. size_t curr_cnt = count();
  223. for (size_t i=0; i<curr_cnt; i++) {
  224. iterator = (iterator + size - 1) % curr_cnt;
  225. subtotal += (float)*(buf + iterator);
  226. }
  227. return curr_cnt ? subtotal / (float)curr_cnt : 0;
  228. }
  229. /**
  230. * @return The arithmetic mean of the most recent 'n' elements of the buffer
  231. */
  232. float mean(size_t n)
  233. {
  234. n = n < size ? n : size;
  235. size_t iterator = begin;
  236. float subtotal = 0;
  237. size_t curr_cnt = count();
  238. for (size_t i=0; i<n; i++) {
  239. iterator = (iterator + size - 1) % curr_cnt;
  240. subtotal += (float)*(buf + iterator);
  241. }
  242. return curr_cnt ? subtotal / (float)curr_cnt : 0;
  243. }
  244. /**
  245. * @return The sample standard deviation of element values
  246. */
  247. float stddev() { return sqrt(variance()); }
  248. /**
  249. * @return The variance of element values
  250. */
  251. float variance()
  252. {
  253. size_t iterator = begin;
  254. float cached_mean = mean();
  255. size_t curr_cnt = count();
  256. if (size) {
  257. T sum_of_squared_deviations = 0;
  258. for (size_t i=0; i<curr_cnt; i++) {
  259. iterator = (iterator + size - 1) % curr_cnt;
  260. float deviation = (buf[i] - cached_mean);
  261. sum_of_squared_deviations += (deviation*deviation);
  262. }
  263. float variance = (float)sum_of_squared_deviations / (float)(size - 1);
  264. return variance;
  265. }
  266. return 0;
  267. }
  268. /**
  269. * @return The number of elements of zero value
  270. */
  271. size_t zeroCount()
  272. {
  273. size_t iterator = begin;
  274. size_t zeros = 0;
  275. size_t curr_cnt = count();
  276. for (size_t i=0; i<curr_cnt; i++) {
  277. iterator = (iterator + size - 1) % curr_cnt;
  278. if (*(buf + iterator) == 0) {
  279. zeros++;
  280. }
  281. }
  282. return zeros;
  283. }
  284. /**
  285. * @param value Value to match against in buffer
  286. * @return The number of values held in the ring buffer which match a given value
  287. */
  288. size_t countValue(T value)
  289. {
  290. size_t iterator = begin;
  291. size_t cnt = 0;
  292. size_t curr_cnt = count();
  293. for (size_t i=0; i<curr_cnt; i++) {
  294. iterator = (iterator + size - 1) % curr_cnt;
  295. if (*(buf + iterator) == value) {
  296. cnt++;
  297. }
  298. }
  299. return cnt;
  300. }
  301. /**
  302. * Print the contents of the buffer
  303. */
  304. void dump()
  305. {
  306. size_t iterator = begin;
  307. for (size_t i=0; i<size; i++) {
  308. iterator = (iterator + size - 1) % size;
  309. if (typeid(T) == typeid(int)) {
  310. //DEBUG_INFO("buf[%2zu]=%2d", iterator, (int)*(buf + iterator));
  311. }
  312. else {
  313. //DEBUG_INFO("buf[%2zu]=%2f", iterator, (float)*(buf + iterator));
  314. }
  315. }
  316. }
  317. };
  318. } // namespace ZeroTier
  319. #endif