1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_RAND_UTIL_H_
6 #define BASE_RAND_UTIL_H_
14 #include "base/base_export.h"
15 #include "build/build_config.h"
19 // Returns a random number in range [0, UINT64_MAX]. Thread-safe.
20 BASE_EXPORT uint64_t RandUint64();
22 // Returns a random number between min and max (inclusive). Thread-safe.
23 BASE_EXPORT int RandInt(int min, int max);
25 // Returns a random number in range [0, range). Thread-safe.
26 BASE_EXPORT uint64_t RandGenerator(uint64_t range);
28 // Returns a random double in range [0, 1). Thread-safe.
29 BASE_EXPORT double RandDouble();
31 // Given input |bits|, convert with maximum precision to a double in
32 // the range [0, 1). Thread-safe.
33 BASE_EXPORT double BitsToOpenEndedUnitInterval(uint64_t bits);
35 // Fills |output_length| bytes of |output| with random data. Thread-safe.
37 // Although implementations are required to use a cryptographically secure
38 // random number source, code outside of base/ that relies on this should use
39 // crypto::RandBytes instead to ensure the requirement is easily discoverable.
40 BASE_EXPORT void RandBytes(void* output, size_t output_length);
42 // Fills a string of length |length| with random data and returns it.
43 // |length| should be nonzero. Thread-safe.
45 // Note that this is a variation of |RandBytes| with a different return type.
46 // The returned string is likely not ASCII/UTF-8. Use with care.
48 // Although implementations are required to use a cryptographically secure
49 // random number source, code outside of base/ that relies on this should use
50 // crypto::RandBytes instead to ensure the requirement is easily discoverable.
51 BASE_EXPORT std::string RandBytesAsString(size_t length);
53 // An STL UniformRandomBitGenerator backed by RandUint64.
54 // TODO(tzik): Consider replacing this with a faster implementation.
55 class RandomBitGenerator {
57 using result_type = uint64_t;
58 static constexpr result_type min() { return 0; }
59 static constexpr result_type max() { return UINT64_MAX; }
60 result_type operator()() const { return RandUint64(); }
62 RandomBitGenerator() = default;
63 ~RandomBitGenerator() = default;
66 // Shuffles [first, last) randomly. Thread-safe.
67 template <typename Itr>
68 void RandomShuffle(Itr first, Itr last) {
69 std::shuffle(first, last, RandomBitGenerator());
73 BASE_EXPORT int GetUrandomFD();
78 #endif // BASE_RAND_UTIL_H_