//===--- Random.h - Utilities for random sampling -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Utilities for random sampling. // //===----------------------------------------------------------------------===// #ifndef LLVM_FUZZMUTATE_RANDOM_H #define LLVM_FUZZMUTATE_RANDOM_H #include #include "llvm/Support/raw_ostream.h" namespace llvm { /// Return a uniformly distributed random value between \c Min and \c Max template T uniform(GenT &Gen, T Min, T Max) { return std::uniform_int_distribution(Min, Max)(Gen); } /// Return a uniformly distributed random value of type \c T template T uniform(GenT &Gen) { return uniform(Gen, std::numeric_limits::min(), std::numeric_limits::max()); } /// Randomly selects an item by sampling into a set with an unknown number of /// elements, which may each be weighted to be more likely choices. template class ReservoirSampler { GenT &RandGen; typename std::remove_const::type Selection = {}; uint64_t TotalWeight = 0; public: ReservoirSampler(GenT &RandGen) : RandGen(RandGen) {} uint64_t totalWeight() const { return TotalWeight; } bool isEmpty() const { return TotalWeight == 0; } const T &getSelection() const { assert(!isEmpty() && "Nothing selected"); return Selection; } explicit operator bool() const { return !isEmpty();} const T &operator*() const { return getSelection(); } /// Sample each item in \c Items with unit weight template ReservoirSampler &sample(RangeT &&Items) { for (auto &I : Items) sample(I, 1); return *this; } /// Sample a single item with the given weight. ReservoirSampler &sample(const T &Item, uint64_t Weight) { if (!Weight) // If the weight is zero, do nothing. return *this; TotalWeight += Weight; // Consider switching from the current element to this one. if (uniform(RandGen, 1, TotalWeight) <= Weight) Selection = Item; return *this; } }; template ()))>::type> ReservoirSampler makeSampler(GenT &RandGen, RangeT &&Items) { ReservoirSampler RS(RandGen); RS.sample(Items); return RS; } template ReservoirSampler makeSampler(GenT &RandGen, const T &Item, uint64_t Weight) { ReservoirSampler RS(RandGen); RS.sample(Item, Weight); return RS; } template ReservoirSampler makeSampler(GenT &RandGen) { return ReservoirSampler(RandGen); } } // End llvm namespace #endif // LLVM_FUZZMUTATE_RANDOM_H