/src/rocksdb/util/random.cc
Line | Count | Source |
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 | | |
7 | | #include "util/random.h" |
8 | | |
9 | | #include <climits> |
10 | | #include <cstdint> |
11 | | #include <cstring> |
12 | | #include <thread> |
13 | | #include <utility> |
14 | | |
15 | | #include "port/likely.h" |
16 | | #include "util/aligned_storage.h" |
17 | | #include "util/thread_local.h" |
18 | | |
19 | 3.14M | #define STORAGE_DECL static thread_local |
20 | | |
21 | | namespace ROCKSDB_NAMESPACE { |
22 | | |
23 | 1.57M | Random* Random::GetTLSInstance() { |
24 | 1.57M | STORAGE_DECL Random* tls_instance; |
25 | 1.57M | STORAGE_DECL aligned_storage<Random>::type tls_instance_bytes; |
26 | | |
27 | 1.57M | auto rv = tls_instance; |
28 | 1.57M | if (UNLIKELY(rv == nullptr)) { |
29 | 4 | size_t seed = std::hash<std::thread::id>()(std::this_thread::get_id()); |
30 | 4 | rv = new (&tls_instance_bytes) Random((uint32_t)seed); |
31 | 4 | tls_instance = rv; |
32 | 4 | } |
33 | 1.57M | return rv; |
34 | 1.57M | } |
35 | | |
36 | 0 | std::string Random::HumanReadableString(int len) { |
37 | 0 | std::string ret; |
38 | 0 | ret.resize(len); |
39 | 0 | for (int i = 0; i < len; ++i) { |
40 | 0 | ret[i] = static_cast<char>('a' + Uniform(26)); |
41 | 0 | } |
42 | 0 | return ret; |
43 | 0 | } |
44 | | |
45 | 0 | std::string Random::RandomString(int len) { |
46 | 0 | std::string ret; |
47 | 0 | ret.resize(len); |
48 | 0 | for (int i = 0; i < len; i++) { |
49 | 0 | ret[i] = static_cast<char>(' ' + Uniform(95)); // ' ' .. '~' |
50 | 0 | } |
51 | 0 | return ret; |
52 | 0 | } |
53 | | |
54 | 0 | std::string Random::RandomBinaryString(int len) { |
55 | 0 | std::string ret; |
56 | 0 | ret.resize(len); |
57 | 0 | for (int i = 0; i < len; i++) { |
58 | | ret[i] = static_cast<char>(Uniform(CHAR_MAX)); |
59 | 0 | } |
60 | 0 | return ret; |
61 | 0 | } |
62 | | |
63 | | } // namespace ROCKSDB_NAMESPACE |