blob: 64f886c74159279257d7b9d4c6c192e457c6a13d [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2014 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Alex Deymoedfa1d42014-04-28 16:53:51 -070016
Gilad Arnold48415f12014-06-27 07:10:58 -070017#ifndef UPDATE_ENGINE_UPDATE_MANAGER_PRNG_H_
18#define UPDATE_ENGINE_UPDATE_MANAGER_PRNG_H_
Alex Deymoedfa1d42014-04-28 16:53:51 -070019
Gilad Arnolde1218812014-05-07 12:21:36 -070020#include <random>
Alex Deymoedfa1d42014-04-28 16:53:51 -070021
Gilad Arnolde1218812014-05-07 12:21:36 -070022#include <base/logging.h>
Alex Deymoedfa1d42014-04-28 16:53:51 -070023
Alex Deymo63784a52014-05-28 10:46:14 -070024namespace chromeos_update_manager {
Alex Deymoedfa1d42014-04-28 16:53:51 -070025
Gilad Arnolde1218812014-05-07 12:21:36 -070026// A thread-safe, unsecure, 32-bit pseudo-random number generator based on
27// std::mt19937.
Alex Deymoedfa1d42014-04-28 16:53:51 -070028class PRNG {
29 public:
Gilad Arnolde1218812014-05-07 12:21:36 -070030 // Initializes the generator with the passed |seed| value.
31 explicit PRNG(uint32_t seed) : gen_(seed) {}
Alex Deymoedfa1d42014-04-28 16:53:51 -070032
Gilad Arnolde1218812014-05-07 12:21:36 -070033 // Returns a random unsigned 32-bit integer.
34 uint32_t Rand() { return gen_(); }
35
36 // Returns a random integer uniformly distributed in the range [min, max].
37 int RandMinMax(int min, int max) {
38 DCHECK_LE(min, max);
39 return std::uniform_int_distribution<>(min, max)(gen_);
40 }
Alex Deymoedfa1d42014-04-28 16:53:51 -070041
42 private:
Gilad Arnolde1218812014-05-07 12:21:36 -070043 // A pseudo-random number generator.
44 std::mt19937 gen_;
Alex Deymoedfa1d42014-04-28 16:53:51 -070045
46 DISALLOW_COPY_AND_ASSIGN(PRNG);
47};
48
Alex Deymo63784a52014-05-28 10:46:14 -070049} // namespace chromeos_update_manager
Alex Deymoedfa1d42014-04-28 16:53:51 -070050
Gilad Arnold48415f12014-06-27 07:10:58 -070051#endif // UPDATE_ENGINE_UPDATE_MANAGER_PRNG_H_