random_provider.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "random_provider.h"
  2. #include <util/random/mersenne.h>
  3. #include <util/random/random.h>
  4. #include <util/system/unaligned_mem.h>
  5. namespace {
  6. void SetV4(TGUID& g) {
  7. g.dw[1] &= 0x0fffffff;
  8. g.dw[1] |= 0x40000000;
  9. g.dw[2] &= 0xffffff3f;
  10. g.dw[2] |= 0x00000080;
  11. }
  12. }
  13. class TDefaultRandomProvider: public IRandomProvider {
  14. public:
  15. ui64 GenRand() noexcept override {
  16. return RandomNumber<ui64>();
  17. }
  18. TGUID GenGuid() noexcept override {
  19. TGUID ret;
  20. CreateGuid(&ret);
  21. return ret;
  22. }
  23. TGUID GenUuid4() noexcept override {
  24. TGUID ret;
  25. WriteUnaligned<ui64>(ret.dw, RandomNumber<ui64>());
  26. WriteUnaligned<ui64>(ret.dw + 2, RandomNumber<ui64>());
  27. SetV4(ret);
  28. return ret;
  29. }
  30. };
  31. class TDeterministicRandomProvider: public IRandomProvider {
  32. public:
  33. TDeterministicRandomProvider(ui64 seed)
  34. : Gen(seed)
  35. {
  36. }
  37. ui64 GenRand() noexcept override {
  38. return Gen.GenRand();
  39. }
  40. TGUID GenGuid() noexcept override {
  41. TGUID ret;
  42. WriteUnaligned<ui64>(ret.dw, Gen.GenRand());
  43. ret.dw[2] = (ui32)Gen.GenRand();
  44. ret.dw[3] = ++GuidCount;
  45. return ret;
  46. }
  47. TGUID GenUuid4() noexcept override {
  48. TGUID ret;
  49. WriteUnaligned<ui64>(ret.dw, Gen.GenRand());
  50. WriteUnaligned<ui64>(ret.dw + 2, Gen.GenRand());
  51. SetV4(ret);
  52. return ret;
  53. }
  54. private:
  55. TMersenne<ui64> Gen;
  56. ui32 GuidCount = 0;
  57. };
  58. TIntrusivePtr<IRandomProvider> CreateDefaultRandomProvider() {
  59. return TIntrusivePtr<IRandomProvider>(new TDefaultRandomProvider());
  60. }
  61. TIntrusivePtr<IRandomProvider> CreateDeterministicRandomProvider(ui64 seed) {
  62. return TIntrusivePtr<IRandomProvider>(new TDeterministicRandomProvider(seed));
  63. }