random.cc 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. #include "util/random.h"
  7. #include <climits>
  8. #include <cstdint>
  9. #include <cstring>
  10. #include <thread>
  11. #include <utility>
  12. #include "port/likely.h"
  13. #include "util/aligned_storage.h"
  14. #include "util/thread_local.h"
  15. #define STORAGE_DECL static thread_local
  16. namespace ROCKSDB_NAMESPACE {
  17. Random* Random::GetTLSInstance() {
  18. STORAGE_DECL Random* tls_instance;
  19. STORAGE_DECL aligned_storage<Random>::type tls_instance_bytes;
  20. auto rv = tls_instance;
  21. if (UNLIKELY(rv == nullptr)) {
  22. size_t seed = std::hash<std::thread::id>()(std::this_thread::get_id());
  23. rv = new (&tls_instance_bytes) Random((uint32_t)seed);
  24. tls_instance = rv;
  25. }
  26. return rv;
  27. }
  28. std::string Random::HumanReadableString(int len) {
  29. std::string ret;
  30. ret.resize(len);
  31. for (int i = 0; i < len; ++i) {
  32. ret[i] = static_cast<char>('a' + Uniform(26));
  33. }
  34. return ret;
  35. }
  36. std::string Random::RandomString(int len) {
  37. std::string ret;
  38. ret.resize(len);
  39. for (int i = 0; i < len; i++) {
  40. ret[i] = static_cast<char>(' ' + Uniform(95)); // ' ' .. '~'
  41. }
  42. return ret;
  43. }
  44. std::string Random::RandomBinaryString(int len) {
  45. std::string ret;
  46. ret.resize(len);
  47. for (int i = 0; i < len; i++) {
  48. ret[i] = static_cast<char>(Uniform(CHAR_MAX));
  49. }
  50. return ret;
  51. }
  52. } // namespace ROCKSDB_NAMESPACE