xref: /freebsd/contrib/llvm-project/compiler-rt/lib/fuzzer/FuzzerRandom.h (revision a90b9d0159070121c221b966469c3e36d912bf82)
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 <random>
15 
16 namespace fuzzer {
17 class Random : public std::minstd_rand {
18  public:
19   Random(unsigned int seed) : std::minstd_rand(seed) {}
20   result_type operator()() { return this->std::minstd_rand::operator()(); }
21   template <typename T>
22   typename std::enable_if<std::is_integral<T>::value, T>::type Rand() {
23     return static_cast<T>(this->operator()());
24   }
25   size_t RandBool() { return this->operator()() % 2; }
26   size_t SkewTowardsLast(size_t n) {
27     size_t T = this->operator()(n * n);
28     size_t Res = static_cast<size_t>(sqrt(T));
29     return Res;
30   }
31   template <typename T>
32   typename std::enable_if<std::is_integral<T>::value, T>::type operator()(T n) {
33     return n ? Rand<T>() % n : 0;
34   }
35   template <typename T>
36   typename std::enable_if<std::is_integral<T>::value, T>::type
37   operator()(T From, T To) {
38     assert(From < To);
39     auto RangeSize = static_cast<unsigned long long>(To) -
40                      static_cast<unsigned long long>(From) + 1;
41     return static_cast<T>(this->operator()(RangeSize) + From);
42   }
43 };
44 
45 }  // namespace fuzzer
46 
47 #endif  // LLVM_FUZZER_RANDOM_H
48