acm_random.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2012 The WebM project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef TEST_ACM_RANDOM_H_
  11. #define TEST_ACM_RANDOM_H_
  12. #include <assert.h>
  13. #include <limits>
  14. #include "third_party/googletest/src/include/gtest/gtest.h"
  15. #include "vpx/vpx_integer.h"
  16. namespace libvpx_test {
  17. class ACMRandom {
  18. public:
  19. ACMRandom() : random_(DeterministicSeed()) {}
  20. explicit ACMRandom(int seed) : random_(seed) {}
  21. void Reset(int seed) { random_.Reseed(seed); }
  22. uint16_t Rand16(void) {
  23. const uint32_t value =
  24. random_.Generate(testing::internal::Random::kMaxRange);
  25. return (value >> 15) & 0xffff;
  26. }
  27. int16_t Rand9Signed(void) {
  28. // Use 9 bits: values between 255 (0x0FF) and -256 (0x100).
  29. const uint32_t value = random_.Generate(512);
  30. return static_cast<int16_t>(value) - 256;
  31. }
  32. uint8_t Rand8(void) {
  33. const uint32_t value =
  34. random_.Generate(testing::internal::Random::kMaxRange);
  35. // There's a bit more entropy in the upper bits of this implementation.
  36. return (value >> 23) & 0xff;
  37. }
  38. uint8_t Rand8Extremes(void) {
  39. // Returns a random value near 0 or near 255, to better exercise
  40. // saturation behavior.
  41. const uint8_t r = Rand8();
  42. return r < 128 ? r << 4 : r >> 4;
  43. }
  44. uint32_t RandRange(const uint32_t range) {
  45. // testing::internal::Random::Generate provides values in the range
  46. // testing::internal::Random::kMaxRange.
  47. assert(range <= testing::internal::Random::kMaxRange);
  48. return random_.Generate(range);
  49. }
  50. int PseudoUniform(int range) { return random_.Generate(range); }
  51. int operator()(int n) { return PseudoUniform(n); }
  52. static int DeterministicSeed(void) { return 0xbaba; }
  53. private:
  54. testing::internal::Random random_;
  55. };
  56. } // namespace libvpx_test
  57. #endif // TEST_ACM_RANDOM_H_