1 //===- FuzzerRandom.h - Internal header for the Fuzzer ----------*- C++ -* ===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // fuzzer::Random 9 //===----------------------------------------------------------------------===// 10 11 #ifndef LLVM_FUZZER_RANDOM_H 12 #define LLVM_FUZZER_RANDOM_H 13 14 #include <cmath> 15 #include <random> 16 17 namespace fuzzer { 18 class Random : public std::minstd_rand { 19 public: 20 Random(unsigned int seed) : std::minstd_rand(seed) {} 21 result_type operator()() { return this->std::minstd_rand::operator()(); } 22 template <typename T> 23 typename std::enable_if<std::is_integral<T>::value, T>::type Rand() { 24 return static_cast<T>(this->operator()()); 25 } 26 size_t RandBool() { return this->operator()() % 2; } 27 size_t SkewTowardsLast(size_t n) { 28 size_t T = this->operator()(n * n); 29 size_t Res = static_cast<size_t>(sqrt(T)); 30 return Res; 31 } 32 template <typename T> 33 typename std::enable_if<std::is_integral<T>::value, T>::type operator()(T n) { 34 return n ? Rand<T>() % n : 0; 35 } 36 template <typename T> 37 typename std::enable_if<std::is_integral<T>::value, T>::type 38 operator()(T From, T To) { 39 assert(From < To); 40 auto RangeSize = static_cast<unsigned long long>(To) - 41 static_cast<unsigned long long>(From) + 1; 42 return static_cast<T>(this->operator()(RangeSize) + From); 43 } 44 }; 45 46 } // namespace fuzzer 47 48 #endif // LLVM_FUZZER_RANDOM_H 49