RingBuffer.hpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 revolving (ring) 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. write(&value, 1);
  160. }
  161. /**
  162. * @return The most recently pushed element on the buffer
  163. */
  164. T get_most_recent() { return *(buf + end); }
  165. /**
  166. * @param dest Destination buffer
  167. * @param n Size (in terms of number of elements) of the destination buffer
  168. * @return Number of elements read from the buffer
  169. */
  170. size_t read(T * dest, size_t n)
  171. {
  172. n = std::min(n, count());
  173. if (n == 0) {
  174. return n;
  175. }
  176. if (wrap) {
  177. wrap = false;
  178. }
  179. const size_t first_chunk = std::min(n, size - begin);
  180. memcpy(dest, buf + begin, first_chunk * sizeof(T));
  181. begin = (begin + first_chunk) % size;
  182. if (first_chunk < n) {
  183. const size_t second_chunk = n - first_chunk;
  184. memcpy(dest + first_chunk, buf + begin, second_chunk * sizeof(T));
  185. begin = (begin + second_chunk) % size;
  186. }
  187. return n;
  188. }
  189. /**
  190. * Return how many elements are in the buffer, O(1).
  191. *
  192. * @return The number of elements in the buffer
  193. */
  194. size_t count()
  195. {
  196. if (end == begin) {
  197. return wrap ? size : 0;
  198. }
  199. else if (end > begin) {
  200. return end - begin;
  201. }
  202. else {
  203. return size + end - begin;
  204. }
  205. }
  206. /**
  207. * @return The number of slots that are unused in the buffer
  208. */
  209. size_t getFree() { return size - count(); }
  210. /**
  211. * @return The arithmetic mean of the contents of the buffer
  212. */
  213. float mean()
  214. {
  215. size_t iterator = begin;
  216. float subtotal = 0;
  217. size_t curr_cnt = count();
  218. for (size_t i=0; i<curr_cnt; i++) {
  219. iterator = (iterator + size - 1) % curr_cnt;
  220. subtotal += (float)*(buf + iterator);
  221. }
  222. return curr_cnt ? subtotal / (float)curr_cnt : 0;
  223. }
  224. /**
  225. * @return The arithmetic mean of the most recent 'n' elements of the buffer
  226. */
  227. float mean(size_t n)
  228. {
  229. n = n < size ? n : size;
  230. size_t iterator = begin;
  231. float subtotal = 0;
  232. size_t curr_cnt = count();
  233. for (size_t i=0; i<n; i++) {
  234. iterator = (iterator + size - 1) % curr_cnt;
  235. subtotal += (float)*(buf + iterator);
  236. }
  237. return curr_cnt ? subtotal / (float)curr_cnt : 0;
  238. }
  239. /**
  240. * @return The sample standard deviation of element values
  241. */
  242. float stddev() { return sqrt(variance()); }
  243. /**
  244. * @return The variance of element values
  245. */
  246. float variance()
  247. {
  248. size_t iterator = begin;
  249. float cached_mean = mean();
  250. size_t curr_cnt = count();
  251. if (size) {
  252. T sum_of_squared_deviations = 0;
  253. for (size_t i=0; i<curr_cnt; i++) {
  254. iterator = (iterator + size - 1) % curr_cnt;
  255. float deviation = (buf[i] - cached_mean);
  256. sum_of_squared_deviations += (deviation*deviation);
  257. }
  258. float variance = (float)sum_of_squared_deviations / (float)(size - 1);
  259. return variance;
  260. }
  261. return 0;
  262. }
  263. /**
  264. * @return The number of elements of zero value
  265. */
  266. size_t zeroCount()
  267. {
  268. size_t iterator = begin;
  269. size_t zeros = 0;
  270. size_t curr_cnt = count();
  271. for (size_t i=0; i<curr_cnt; i++) {
  272. iterator = (iterator + size - 1) % curr_cnt;
  273. if (*(buf + iterator) == 0) {
  274. zeros++;
  275. }
  276. }
  277. return zeros;
  278. }
  279. /**
  280. * @param value Value to match against in buffer
  281. * @return The number of values held in the ring buffer which match a given value
  282. */
  283. size_t countValue(T value)
  284. {
  285. size_t iterator = begin;
  286. size_t cnt = 0;
  287. size_t curr_cnt = count();
  288. for (size_t i=0; i<curr_cnt; i++) {
  289. iterator = (iterator + size - 1) % curr_cnt;
  290. if (*(buf + iterator) == value) {
  291. cnt++;
  292. }
  293. }
  294. return cnt;
  295. }
  296. /**
  297. * Print the contents of the buffer
  298. */
  299. void dump()
  300. {
  301. size_t iterator = begin;
  302. for (size_t i=0; i<size; i++) {
  303. iterator = (iterator + size - 1) % size;
  304. if (typeid(T) == typeid(int)) {
  305. //DEBUG_INFO("buf[%2zu]=%2d", iterator, (int)*(buf + iterator));
  306. }
  307. else {
  308. //DEBUG_INFO("buf[%2zu]=%2f", iterator, (float)*(buf + iterator));
  309. }
  310. }
  311. }
  312. };
  313. } // namespace ZeroTier
  314. #endif