leveldb
Public Member Functions | Private Attributes | List of all members
leveldb::Random Class Reference

#include <random.h>

Public Member Functions

 Random (uint32_t s)
 
uint32_t Next ()
 
uint32_t Uniform (int n)
 
bool OneIn (int n)
 
uint32_t Skewed (int max_log)
 

Private Attributes

uint32_t seed_
 

Detailed Description

Definition at line 15 of file random.h.

Constructor & Destructor Documentation

§ Random()

leveldb::Random::Random ( uint32_t  s)
inlineexplicit

Definition at line 19 of file random.h.

19  : seed_(s & 0x7fffffffu) {
20  // Avoid bad seeds.
21  if (seed_ == 0 || seed_ == 2147483647L) {
22  seed_ = 1;
23  }
24  }
uint32_t seed_
Definition: random.h:17

Member Function Documentation

§ Next()

uint32_t leveldb::Random::Next ( )
inline

Definition at line 25 of file random.h.

25  {
26  static const uint32_t M = 2147483647L; // 2^31-1
27  static const uint64_t A = 16807; // bits 14, 8, 7, 5, 2, 1, 0
28  // We are computing
29  // seed_ = (seed_ * A) % M, where M = 2^31-1
30  //
31  // seed_ must not be zero or M, or else all subsequent computed values
32  // will be zero or M respectively. For all other values, seed_ will end
33  // up cycling through every number in [1,M-1]
34  uint64_t product = seed_ * A;
35 
36  // Compute (product % M) using the fact that ((x << 31) % M) == x.
37  seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
38  // The first reduction may overflow by 1 bit, so we may need to
39  // repeat. mod == M is not possible; using > allows the faster
40  // sign-bit-based test.
41  if (seed_ > M) {
42  seed_ -= M;
43  }
44  return seed_;
45  }
uint32_t seed_
Definition: random.h:17
Here is the caller graph for this function:

§ OneIn()

bool leveldb::Random::OneIn ( int  n)
inline

Definition at line 52 of file random.h.

52 { return (Next() % n) == 0; }
uint32_t Next()
Definition: random.h:25
Here is the call graph for this function:
Here is the caller graph for this function:

§ Skewed()

uint32_t leveldb::Random::Skewed ( int  max_log)
inline

Definition at line 57 of file random.h.

57  {
58  return Uniform(1 << Uniform(max_log + 1));
59  }
uint32_t Uniform(int n)
Definition: random.h:48
Here is the call graph for this function:
Here is the caller graph for this function:

§ Uniform()

uint32_t leveldb::Random::Uniform ( int  n)
inline

Definition at line 48 of file random.h.

48 { return Next() % n; }
uint32_t Next()
Definition: random.h:25
Here is the call graph for this function:
Here is the caller graph for this function:

Member Data Documentation

§ seed_

uint32_t leveldb::Random::seed_
private

Definition at line 17 of file random.h.


The documentation for this class was generated from the following file: