MongoDB C++ Driver  legacy-1.1.2
random.h
1 // random.h
2 
3 /* Copyright 2012 10gen Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #pragma once
19 
20 #include "mongo/platform/cstdint.h"
21 
22 namespace mongo {
23 
27 class PseudoRandom {
28 public:
29  PseudoRandom(int32_t seed);
30 
31  PseudoRandom(uint32_t seed);
32 
33  PseudoRandom(int64_t seed);
34 
35  int32_t nextInt32();
36 
37  int64_t nextInt64();
38 
42  int32_t nextInt32(int32_t max) {
43  return static_cast<uint32_t>(nextInt32()) % static_cast<uint32_t>(max);
44  }
45 
49  int64_t nextInt64(int64_t max) {
50  return static_cast<uint64_t>(nextInt64()) % static_cast<uint64_t>(max);
51  }
52 
58  intptr_t operator()(intptr_t max) {
59  if (sizeof(intptr_t) == 4)
60  return static_cast<intptr_t>(nextInt32(static_cast<int32_t>(max)));
61  return static_cast<intptr_t>(nextInt64(static_cast<int64_t>(max)));
62  }
63 
64 private:
65  void _init(uint32_t seed);
66 
67  uint32_t nextUInt32();
68 
69  uint32_t _x;
70  uint32_t _y;
71  uint32_t _z;
72  uint32_t _w;
73 };
74 
80 class SecureRandom {
81 public:
82  virtual ~SecureRandom();
83 
84  virtual int64_t nextInt64() = 0;
85 
86  static SecureRandom* create();
87 };
88 } // namespace mongo
More secure random numbers Suitable for nonce/crypto Slower than PseudoRandom, so only use when reall...
Definition: random.h:80
Utility functions for parsing numbers from strings.
Definition: compare_numbers.h:20
int64_t nextInt64(int64_t max)
Definition: random.h:49
intptr_t operator()(intptr_t max)
Definition: random.h:58
int32_t nextInt32(int32_t max)
Definition: random.h:42
Uses http://en.wikipedia.org/wiki/Xorshift.
Definition: random.h:27