FuzzerRandom.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. #ifndef LLVM_FUZZER_RANDOM_H
  11. #define LLVM_FUZZER_RANDOM_H
  12. #include <random>
  13. namespace fuzzer {
  14. class Random : public std::minstd_rand {
  15. public:
  16. Random(unsigned int seed) : std::minstd_rand(seed) {}
  17. result_type operator()() { return this->std::minstd_rand::operator()(); }
  18. template <typename T>
  19. typename std::enable_if<std::is_integral<T>::value, T>::type Rand() {
  20. return static_cast<T>(this->operator()());
  21. }
  22. size_t RandBool() { return this->operator()() % 2; }
  23. size_t SkewTowardsLast(size_t n) {
  24. size_t T = this->operator()(n * n);
  25. size_t Res = static_cast<size_t>(sqrt(T));
  26. return Res;
  27. }
  28. template <typename T>
  29. typename std::enable_if<std::is_integral<T>::value, T>::type operator()(T n) {
  30. return n ? Rand<T>() % n : 0;
  31. }
  32. template <typename T>
  33. typename std::enable_if<std::is_integral<T>::value, T>::type
  34. operator()(T From, T To) {
  35. assert(From < To);
  36. auto RangeSize = static_cast<unsigned long long>(To) -
  37. static_cast<unsigned long long>(From) + 1;
  38. return static_cast<T>(this->operator()(RangeSize) + From);
  39. }
  40. };
  41. } // namespace fuzzer
  42. #endif // LLVM_FUZZER_RANDOM_H