blob: 722933d980c751af5744157c4a07bff4ede260fb [file] [log] [blame]
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001// Copyright 2021 The Tint Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "src/tint/fuzzers/mersenne_twister_engine.h"
16
17#include <algorithm>
18#include <cassert>
19
dan sinclair22b4dd22023-07-21 00:40:07 +000020#include "src/tint/utils/math/hash.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000021
dan sinclair62a1d712022-04-07 17:46:04 +000022namespace tint::fuzzers {
Ryan Harrisondbc13af2022-02-21 15:19:07 +000023
24namespace {
25
26/// Generate integer from uniform distribution
27/// @tparam I - integer type
28/// @param engine - random number engine to use
29/// @param lower - Lower bound of integer generated
30/// @param upper - Upper bound of integer generated
31/// @returns i, where lower <= i < upper
32template <typename I>
33I RandomInteger(std::mt19937_64* engine, I lower, I upper) {
dan sinclair41e4d9a2022-05-01 14:40:55 +000034 assert(lower < upper && "|lower| must be strictly less than |upper|");
35 return std::uniform_int_distribution<I>(lower, upper - 1)(*engine);
Ryan Harrisondbc13af2022-02-21 15:19:07 +000036}
37
38} // namespace
39
40MersenneTwisterEngine::MersenneTwisterEngine(uint64_t seed) : engine_(seed) {}
41
42uint32_t MersenneTwisterEngine::RandomUInt32(uint32_t lower, uint32_t upper) {
dan sinclair41e4d9a2022-05-01 14:40:55 +000043 return RandomInteger(&engine_, lower, upper);
Ryan Harrisondbc13af2022-02-21 15:19:07 +000044}
45
46uint64_t MersenneTwisterEngine::RandomUInt64(uint64_t lower, uint64_t upper) {
dan sinclair41e4d9a2022-05-01 14:40:55 +000047 return RandomInteger(&engine_, lower, upper);
Ryan Harrisondbc13af2022-02-21 15:19:07 +000048}
49
50void MersenneTwisterEngine::RandomNBytes(uint8_t* dest, size_t n) {
dan sinclair41e4d9a2022-05-01 14:40:55 +000051 assert(dest && "|dest| must not be nullptr");
52 std::generate(dest, dest + n,
53 std::independent_bits_engine<std::mt19937_64, 8, uint8_t>(engine_));
Ryan Harrisondbc13af2022-02-21 15:19:07 +000054}
55
dan sinclair62a1d712022-04-07 17:46:04 +000056} // namespace tint::fuzzers