random_number_generator.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef MEDIA_LEARNING_IMPL_RANDOM_NUMBER_GENERATOR_H_
  5. #define MEDIA_LEARNING_IMPL_RANDOM_NUMBER_GENERATOR_H_
  6. #include <cstdint>
  7. #include "base/component_export.h"
  8. #include "base/memory/raw_ptr.h"
  9. namespace media {
  10. // Class to encapsulate a random number generator with an implementation for
  11. // tests that provides repeatable, platform-independent sequences.
  12. class COMPONENT_EXPORT(LEARNING_IMPL) RandomNumberGenerator {
  13. public:
  14. RandomNumberGenerator() = default;
  15. RandomNumberGenerator(const RandomNumberGenerator&) = delete;
  16. RandomNumberGenerator& operator=(const RandomNumberGenerator&) = delete;
  17. virtual ~RandomNumberGenerator() = default;
  18. // Return a random generator that will return unpredictable values in the
  19. // //base/rand_util.h sense. See TestRandomGenerator if you'd like one that's
  20. // more predictable for tests.
  21. static RandomNumberGenerator* Default();
  22. // Taken from rand_util.h
  23. // Returns a random number in range [0, UINT64_MAX]. Thread-safe.
  24. virtual uint64_t Generate() = 0;
  25. // Returns a random number in range [0, range). Thread-safe.
  26. uint64_t Generate(uint64_t range);
  27. // Returns a floating point number in the range [0, range). Thread-safe.
  28. // This isn't an overload of Generate() to be sure that one isn't surprised by
  29. // the result.
  30. double GenerateDouble(double range);
  31. };
  32. // Handy mix-in class if you want to support rng injection.
  33. class COMPONENT_EXPORT(LEARNING_IMPL) HasRandomNumberGenerator {
  34. public:
  35. // If |rng| is null, then we'll create a new one as a convenience.
  36. explicit HasRandomNumberGenerator(RandomNumberGenerator* rng = nullptr);
  37. ~HasRandomNumberGenerator();
  38. void SetRandomNumberGeneratorForTesting(RandomNumberGenerator* rng);
  39. protected:
  40. RandomNumberGenerator* rng() const { return rng_; }
  41. private:
  42. raw_ptr<RandomNumberGenerator> rng_ = nullptr;
  43. };
  44. } // namespace media
  45. #endif // MEDIA_LEARNING_IMPL_RANDOM_NUMBER_GENERATOR_H_