GCC Code Coverage Report
Directory: cvmfs/ Exec Total Coverage
File: cvmfs/prng.h Lines: 15 15 100.0 %
Date: 2019-02-03 02:48:13 Branches: 1 2 50.0 %

Line Branch Exec Source
1
/**
2
 * This file is part of the CernVM File System.
3
 *
4
 * A simple linear congruential pseudo number generator.  Thread-safe since
5
 * there is no global state like with random().
6
 */
7
8
#ifndef CVMFS_PRNG_H_
9
#define CVMFS_PRNG_H_
10
11
#include <stdint.h>
12
#include <sys/time.h>
13
14
#include <cassert>
15
#include <cstdlib>
16
17
#ifdef CVMFS_NAMESPACE_GUARD
18
namespace CVMFS_NAMESPACE_GUARD {
19
#endif
20
21
/**
22
 * Pseudo Random Number Generator.  See: TAoCP, volume 2
23
 */
24
class Prng {
25
 public:
26
8004433
  Prng() {
27
8004433
    state_ = 0;
28
8004433
  }
29
30
8002314
  void InitSeed(const uint64_t seed) {
31
8002314
    state_ = seed;
32
8002314
  }
33
34
1913
  void InitLocaltime() {
35
    struct timeval tv_now;
36
1913
    int retval = gettimeofday(&tv_now, NULL);
37
1913
    assert(retval == 0);
38
1913
    state_ = tv_now.tv_usec;
39
1913
  }
40
41
  /**
42
   * Returns random number in [0..boundary-1]
43
   */
44
6661429410
  uint32_t Next(const uint64_t boundary) {
45
6661429410
    state_ = a*state_ + c;
46
    double scaled_val =
47
      static_cast<double>(state_) * static_cast<double>(boundary) /
48
6661429410
      static_cast<double>(18446744073709551616.0);
49
6661429410
    return (uint32_t)scaled_val % boundary;
50
  }
51
52
 private:
53
  // Magic numbers from MMIX
54
  // static const uint64_t m = 2^64;
55
  static const uint64_t a = 6364136223846793005LLU;
56
  static const uint64_t c = 1442695040888963407LLU;
57
  uint64_t state_;
58
};  // class Prng
59
60
#ifdef CVMFS_NAMESPACE_GUARD
61
}  // namespace CVMFS_NAMESPACE_GUARD
62
#endif
63
64
#endif  // CVMFS_PRNG_H_