| // Copyright 2017 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| #ifndef COBALT_SRC_LIB_UTIL_CLOCK_H_ |
| #define COBALT_SRC_LIB_UTIL_CLOCK_H_ |
| |
| #include <chrono> |
| #include <memory> |
| #include <optional> |
| #include <string> |
| |
| #include "src/public/lib/clock_interfaces.h" |
| #include "src/public/lib/compat/clock.h" |
| #include "src/public/lib/statusor/statusor.h" |
| |
| namespace cobalt::util { |
| |
| // A clock that returns the real system time. |
| class SystemClock : public SystemClockInterface { |
| public: |
| std::chrono::system_clock::time_point now() override { return std::chrono::system_clock::now(); } |
| }; |
| |
| // Allows us to mock out a clock for tests. |
| // A clock that returns the real system time. |
| class SteadyClock : public SteadyClockInterface { |
| public: |
| std::chrono::steady_clock::time_point now() override { return std::chrono::steady_clock::now(); } |
| }; |
| |
| // A clock that returns the boot time, i.e. the amount of time since the OS booted. |
| class BootClock : public BootClockInterface { |
| public: |
| compat::boot_clock::time_point now() override { return compat::boot_clock::now(); } |
| }; |
| |
| // A wrapper for a SystemClockInterface that is always accurate. |
| class AlwaysAccurateClock : public util::ValidatedClockInterface { |
| public: |
| explicit AlwaysAccurateClock(std::unique_ptr<SystemClockInterface> system_clock) |
| : system_clock_(std::move(system_clock)) {} |
| |
| std::optional<std::chrono::system_clock::time_point> now() override { |
| return system_clock_->now(); |
| } |
| |
| private: |
| std::unique_ptr<SystemClockInterface> system_clock_; |
| }; |
| |
| // A CivilTimeConverterInterface that converts a time point to a time struct with respect to |
| // UTC, regardless of the time zone identifier that is passed to `civil_time()`. |
| // |
| // This is the fallback converter that is used to compute civil times for metrics with the |
| // OTHER_TIME_ZONE policy in the case where no CivilTimeConverterInterface was provided to the |
| // CobaltService. |
| class UtcTimeConverter : public util::CivilTimeConverterInterface { |
| public: |
| [[nodiscard]] lib::statusor::StatusOr<std::tm> civil_time( |
| std::chrono::system_clock::time_point time, const std::string& /*time_zone*/) const override { |
| std::time_t time_t = std::chrono::system_clock::to_time_t(time); |
| std::tm time_struct; |
| gmtime_r(&time_t, &time_struct); |
| return time_struct; |
| } |
| }; |
| |
| } // namespace cobalt::util |
| |
| #endif // COBALT_SRC_LIB_UTIL_CLOCK_H_ |