1 /* 2 * Copyright 2020 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef FCP_BASE_SIMULATED_CLOCK_H_ 18 #define FCP_BASE_SIMULATED_CLOCK_H_ 19 20 #include "fcp/base/clock.h" 21 22 namespace fcp { 23 24 /* 25 * A simulated clock is a concrete Clock implementation that does not "tick" 26 * on its own. Time is advanced by explicit calls to the AdvanceTime() or 27 * SetTime() functions. 28 */ 29 class SimulatedClock : public Clock { 30 public: 31 // Construct SimulatedClock with a specific initial time. SimulatedClock(absl::Time t)32 explicit SimulatedClock(absl::Time t) : now_(t) {} 33 34 // Construct SimulatedClock with default initial time (1970-01-01 00:00:00) SimulatedClock()35 SimulatedClock() : SimulatedClock(absl::UnixEpoch()) {} 36 37 // Returns the simulated time. 38 absl::Time Now() override; 39 40 // Sleeps until the specified duration has elapsed according to this clock. 41 void Sleep(absl::Duration d) override; 42 43 // Sets the simulated time. Wakes up any waiters whose deadlines have now 44 // expired. 45 void SetTime(absl::Time t); 46 47 // Advances the simulated time. Wakes up any waiters whose deadlines have now 48 // expired. 49 void AdvanceTime(absl::Duration d); 50 51 private: 52 // Returns the simulated time (called internally from the base class). 53 absl::Time NowLocked() override; 54 55 // No specific scheduling is needed for SimulatedClock. ScheduleWakeup(absl::Time wakeup_time)56 void ScheduleWakeup(absl::Time wakeup_time) override {} 57 58 absl::Time now_ ABSL_GUARDED_BY(mutex()); 59 }; 60 61 } // namespace fcp 62 63 #endif // FCP_BASE_SIMULATED_CLOCK_H_ 64