Home | History | Annotate | Download | only in base
      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.
      4 
      5 #ifndef BASE_RAND_UTIL_H_
      6 #define BASE_RAND_UTIL_H_
      7 
      8 #include <stddef.h>
      9 #include <stdint.h>
     10 
     11 #include <string>
     12 
     13 #include "base/base_export.h"
     14 #include "build/build_config.h"
     15 
     16 namespace base {
     17 
     18 // Returns a random number in range [0, UINT64_MAX]. Thread-safe.
     19 BASE_EXPORT uint64_t RandUint64();
     20 
     21 // Returns a random number between min and max (inclusive). Thread-safe.
     22 BASE_EXPORT int RandInt(int min, int max);
     23 
     24 // Returns a random number in range [0, range).  Thread-safe.
     25 //
     26 // Note that this can be used as an adapter for std::random_shuffle():
     27 // Given a pre-populated |std::vector<int> myvector|, shuffle it as
     28 //   std::random_shuffle(myvector.begin(), myvector.end(), base::RandGenerator);
     29 BASE_EXPORT uint64_t RandGenerator(uint64_t range);
     30 
     31 // Returns a random double in range [0, 1). Thread-safe.
     32 BASE_EXPORT double RandDouble();
     33 
     34 // Given input |bits|, convert with maximum precision to a double in
     35 // the range [0, 1). Thread-safe.
     36 BASE_EXPORT double BitsToOpenEndedUnitInterval(uint64_t bits);
     37 
     38 // Fills |output_length| bytes of |output| with random data.
     39 //
     40 // WARNING:
     41 // Do not use for security-sensitive purposes.
     42 // See crypto/ for cryptographically secure random number generation APIs.
     43 BASE_EXPORT void RandBytes(void* output, size_t output_length);
     44 
     45 // Fills a string of length |length| with random data and returns it.
     46 // |length| should be nonzero.
     47 //
     48 // Note that this is a variation of |RandBytes| with a different return type.
     49 // The returned string is likely not ASCII/UTF-8. Use with care.
     50 //
     51 // WARNING:
     52 // Do not use for security-sensitive purposes.
     53 // See crypto/ for cryptographically secure random number generation APIs.
     54 BASE_EXPORT std::string RandBytesAsString(size_t length);
     55 
     56 #if defined(OS_POSIX)
     57 BASE_EXPORT int GetUrandomFD();
     58 #endif
     59 
     60 }  // namespace base
     61 
     62 #endif  // BASE_RAND_UTIL_H_
     63