CMWC4096.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_CMWC4096_HPP
  28. #define ZT_CMWC4096_HPP
  29. #include <stdint.h>
  30. #include "Utils.hpp"
  31. namespace ZeroTier {
  32. /**
  33. * Complement Multiply With Carry random number generator
  34. *
  35. * Based on original code posted to Usenet in the public domain by
  36. * George Marsaglia. Period is approximately 2^131086.
  37. *
  38. * This is not used for cryptographic purposes but for a very fast
  39. * and high-quality PRNG elsewhere in the code.
  40. */
  41. class CMWC4096
  42. {
  43. public:
  44. /**
  45. * Construct and initialize from secure random source
  46. */
  47. CMWC4096()
  48. throw()
  49. {
  50. Utils::getSecureRandom(Q,sizeof(Q));
  51. Utils::getSecureRandom(&c,sizeof(c));
  52. c %= 809430660;
  53. i = 4095;
  54. }
  55. inline uint32_t next32()
  56. throw()
  57. {
  58. uint32_t __i = ++i & 4095;
  59. const uint64_t t = (18782ULL * (uint64_t)Q[__i]) + (uint64_t)c;
  60. c = (uint32_t)(t >> 32);
  61. uint32_t x = c + (uint32_t)t;
  62. const uint32_t p = (uint32_t)(x < c); x += p; c += p;
  63. return (Q[__i] = 0xfffffffe - x);
  64. }
  65. inline uint64_t next64()
  66. throw()
  67. {
  68. return ((((uint64_t)next32()) << 32) ^ (uint64_t)next32());
  69. }
  70. inline double nextDouble()
  71. throw()
  72. {
  73. return ((double)(next32()) / 4294967296.0);
  74. }
  75. private:
  76. uint32_t Q[4096];
  77. uint32_t c;
  78. uint32_t i;
  79. };
  80. } // namespace ZeroTier
  81. #endif