fake_clock.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright 2016 The WebRTC 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 RTC_BASE_FAKE_CLOCK_H_
  11. #define RTC_BASE_FAKE_CLOCK_H_
  12. #include <stdint.h>
  13. #include "api/units/time_delta.h"
  14. #include "api/units/timestamp.h"
  15. #include "rtc_base/synchronization/mutex.h"
  16. #include "rtc_base/thread_annotations.h"
  17. #include "rtc_base/time_utils.h"
  18. namespace rtc {
  19. // Fake clock for use with unit tests, which does not tick on its own.
  20. // Starts at time 0.
  21. //
  22. // TODO(deadbeef): Unify with webrtc::SimulatedClock.
  23. class FakeClock : public ClockInterface {
  24. public:
  25. FakeClock() = default;
  26. FakeClock(const FakeClock&) = delete;
  27. FakeClock& operator=(const FakeClock&) = delete;
  28. ~FakeClock() override = default;
  29. // ClockInterface implementation.
  30. int64_t TimeNanos() const override;
  31. // Methods that can be used by the test to control the time.
  32. // Should only be used to set a time in the future.
  33. void SetTime(webrtc::Timestamp new_time);
  34. void AdvanceTime(webrtc::TimeDelta delta);
  35. private:
  36. mutable webrtc::Mutex lock_;
  37. int64_t time_ns_ RTC_GUARDED_BY(lock_) = 0;
  38. };
  39. class ThreadProcessingFakeClock : public ClockInterface {
  40. public:
  41. int64_t TimeNanos() const override { return clock_.TimeNanos(); }
  42. void SetTime(webrtc::Timestamp time);
  43. void AdvanceTime(webrtc::TimeDelta delta);
  44. private:
  45. FakeClock clock_;
  46. };
  47. // Helper class that sets itself as the global clock in its constructor and
  48. // unsets it in its destructor.
  49. class ScopedBaseFakeClock : public FakeClock {
  50. public:
  51. ScopedBaseFakeClock();
  52. ~ScopedBaseFakeClock() override;
  53. private:
  54. ClockInterface* prev_clock_;
  55. };
  56. // TODO(srte): Rename this to reflect that it also does thread processing.
  57. class ScopedFakeClock : public ThreadProcessingFakeClock {
  58. public:
  59. ScopedFakeClock();
  60. ~ScopedFakeClock() override;
  61. private:
  62. ClockInterface* prev_clock_;
  63. };
  64. } // namespace rtc
  65. #endif // RTC_BASE_FAKE_CLOCK_H_