pseudo_random_generator.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright (c) 2019 Google LLC
  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. #include "source/fuzz/pseudo_random_generator.h"
  15. #include <cassert>
  16. namespace spvtools {
  17. namespace fuzz {
  18. PseudoRandomGenerator::PseudoRandomGenerator(uint32_t seed) : mt_(seed) {}
  19. PseudoRandomGenerator::~PseudoRandomGenerator() = default;
  20. uint32_t PseudoRandomGenerator::RandomUint32(uint32_t bound) {
  21. assert(bound > 0 && "Bound must be positive");
  22. return std::uniform_int_distribution<uint32_t>(0, bound - 1)(mt_);
  23. }
  24. uint64_t PseudoRandomGenerator::RandomUint64(uint64_t bound) {
  25. assert(bound > 0 && "Bound must be positive");
  26. return std::uniform_int_distribution<uint64_t>(0, bound - 1)(mt_);
  27. }
  28. bool PseudoRandomGenerator::RandomBool() {
  29. return static_cast<bool>(std::uniform_int_distribution<>(0, 1)(mt_));
  30. }
  31. uint32_t PseudoRandomGenerator::RandomPercentage() {
  32. // We use 101 because we want a result in the closed interval [0, 100], and
  33. // RandomUint32 is not inclusive of its bound.
  34. return RandomUint32(101);
  35. }
  36. double PseudoRandomGenerator::RandomDouble() {
  37. return std::uniform_real_distribution<double>(0.0, 1.0)(mt_);
  38. }
  39. } // namespace fuzz
  40. } // namespace spvtools