random_creater.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Tencent is pleased to support the open source community by making wwsearch
  3. * available.
  4. *
  5. * Copyright (C) 2018-present Tencent. All Rights Reserved.
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  8. * use this file except in compliance with the License. You may obtain a copy of
  9. * the License at
  10. *
  11. * https://opensource.org/licenses/Apache-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OF ANY KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations under the License.
  17. */
  18. #pragma once
  19. #include <assert.h>
  20. #include <fcntl.h>
  21. #include <stdint.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <sys/stat.h>
  25. #include <sys/types.h>
  26. #include <unistd.h>
  27. #include <string>
  28. namespace wwsearch {
  29. class RandomCreater {
  30. private:
  31. uint64_t count_;
  32. uint64_t seed1_;
  33. uint64_t seed2_;
  34. std::string temp_str_;
  35. public:
  36. RandomCreater() {}
  37. virtual ~RandomCreater() {}
  38. inline int Init(unsigned int seed) {
  39. int fd;
  40. fd = open("/dev/urandom", 0);
  41. if (fd < 0) {
  42. return -1;
  43. }
  44. assert(read(fd, &seed1_, 4) > 0);
  45. assert(read(fd, &seed2_, 4) > 0);
  46. close(fd);
  47. count_ = 0;
  48. return 0;
  49. }
  50. inline uint32_t GetUInt32() {
  51. count_++;
  52. if (count_ % 2 == 0) {
  53. seed1_ = (seed1_ * 25214903917UL + 11UL) % (1UL << 48);
  54. return seed1_;
  55. } else {
  56. seed2_ = (seed2_ * 25214903917UL + 11UL) % (1UL << 48);
  57. return seed2_;
  58. }
  59. }
  60. inline uint64_t GetUInt64() {
  61. uint64_t v;
  62. v = GetUInt32();
  63. v <<= 32;
  64. v |= GetUInt32();
  65. return v;
  66. }
  67. std::string &GetString(size_t len) {
  68. temp_str_.clear();
  69. uint32_t v;
  70. while (len > 4) {
  71. v = GetUInt32();
  72. temp_str_.append((const char *)&v, 4);
  73. len -= 4;
  74. }
  75. v = GetUInt32();
  76. temp_str_.append((const char *)&v, len);
  77. return temp_str_;
  78. }
  79. };
  80. } // namespace wwsearch