1 // 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 #ifndef FUZZERS_TINT_AST_FUZZER_PROBABILITY_CONTEXT_H_ 16 #define FUZZERS_TINT_AST_FUZZER_PROBABILITY_CONTEXT_H_ 17 18 #include <utility> 19 #include <vector> 20 21 #include "fuzzers/random_generator.h" 22 23 namespace tint { 24 namespace fuzzers { 25 namespace ast_fuzzer { 26 27 /// This class is intended to be used by the `MutationFinder`s to introduce some 28 /// variance to the mutation process. 29 class ProbabilityContext { 30 public: 31 /// Initializes this instance with a random number generator. 32 /// @param generator - must not be a `nullptr`. Must remain in scope as long 33 /// as this 34 /// instance exists. 35 explicit ProbabilityContext(RandomGenerator* generator); 36 37 /// Get random bool with even odds 38 /// @returns true 50% of the time and false %50 of time. RandomBool()39 bool RandomBool() { return generator_->GetBool(); } 40 41 /// Get random bool with weighted odds 42 /// @param percentage - likelihood of true being returned 43 /// @returns true |percentage|% of the time, and false (100 - |percentage|)% 44 /// of the time. ChoosePercentage(uint32_t percentage)45 bool ChoosePercentage(uint32_t percentage) { 46 return generator_->GetWeightedBool(percentage); 47 } 48 49 /// Returns a random value in the range `[0; arr.size())`. 50 /// @tparam T - type of the elements in the vector. 51 /// @param arr - may not be empty. 52 /// @return the random index in the `arr`. 53 template <typename T> GetRandomIndex(const std::vector<T> & arr)54 size_t GetRandomIndex(const std::vector<T>& arr) { 55 return static_cast<size_t>(generator_->GetUInt64(arr.size())); 56 } 57 58 /// @return the probability of replacing some identifier with some other one. GetChanceOfReplacingIdentifiers()59 uint32_t GetChanceOfReplacingIdentifiers() const { 60 return chance_of_replacing_identifiers_; 61 } 62 63 private: 64 /// @param range - a pair of integers `a` and `b` s.t. `a <= b`. 65 /// @return an random number in the range `[a; b]`. 66 uint32_t RandomFromRange(std::pair<uint32_t, uint32_t> range); 67 68 RandomGenerator* generator_; 69 70 uint32_t chance_of_replacing_identifiers_; 71 }; 72 73 } // namespace ast_fuzzer 74 } // namespace fuzzers 75 } // namespace tint 76 77 #endif // FUZZERS_TINT_AST_FUZZER_PROBABILITY_CONTEXT_H_ 78