From 6413588df62d2fcc835ad5b570a57b0c96e102d7 Mon Sep 17 00:00:00 2001 From: falsycat Date: Sun, 6 Aug 2023 16:02:52 +0900 Subject: [PATCH] add subsys::Clock --- core/CMakeLists.txt | 2 ++ core/clock.hh | 27 +++++++++++++++++++++++++++ core/clock_test.cc | 20 ++++++++++++++++++++ iface/subsys/clock.hh | 21 +++++++++++++++++++++ 4 files changed, 70 insertions(+) create mode 100644 core/clock.hh create mode 100644 core/clock_test.cc create mode 100644 iface/subsys/clock.hh diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 210de03..5e7ac83 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -16,6 +16,7 @@ target_sources(nf7_core luajit/context.hh luajit/lambda.hh luajit/thread.hh + clock.hh version.hh ) @@ -27,6 +28,7 @@ target_sources(nf7_core_test luajit/lambda_test.cc luajit/thread_test.cc luajit/thread_test.hh + clock_test.cc ) target_link_libraries(nf7_core_test PRIVATE diff --git a/core/clock.hh b/core/clock.hh new file mode 100644 index 0000000..ce08898 --- /dev/null +++ b/core/clock.hh @@ -0,0 +1,27 @@ +// No copyright +#pragma once + +#include "iface/subsys/clock.hh" + +namespace nf7::core { + +class Clock : public subsys::Clock { + public: + static Time GetCurrentTime() noexcept { + return std::chrono::time_point_cast< + Resolution>(std::chrono::system_clock::now()); + } + + public: + explicit Clock(Time now = GetCurrentTime()) noexcept + : subsys::Clock("Clock"), now_(now) { } + + void Tick(Time now = GetCurrentTime()) noexcept { now_ = now; } + + Time now() const noexcept { return now_; } + + private: + Time now_; +}; + +} // namespace nf7::core diff --git a/core/clock_test.cc b/core/clock_test.cc new file mode 100644 index 0000000..eff015a --- /dev/null +++ b/core/clock_test.cc @@ -0,0 +1,20 @@ +// No copyright +#include "core/clock.hh" + +#include + +#include + + +using namespace std::literals; + +TEST(Clock, now) { + nf7::core::Clock sut {nf7::core::Clock::Time {0ms}}; + EXPECT_EQ(sut.now(), nf7::core::Clock::Time {0ms}); +} + +TEST(Clock, Tick) { + nf7::core::Clock sut {nf7::core::Clock::Time {0ms}}; + sut.Tick(nf7::core::Clock::Time {1ms}); + EXPECT_EQ(sut.now(), nf7::core::Clock::Time {1ms}); +} diff --git a/iface/subsys/clock.hh b/iface/subsys/clock.hh new file mode 100644 index 0000000..d07927a --- /dev/null +++ b/iface/subsys/clock.hh @@ -0,0 +1,21 @@ +// No copyright +#pragma once + +#include + +#include "iface/subsys/interface.hh" + + +namespace nf7::subsys { + +class Clock : public Interface { + public: + using Resolution = std::chrono::milliseconds; + using Time = std::chrono::sys_time; + + using Interface::Interface; + + virtual Time now() const noexcept = 0; +}; + +} // namespace nf7::subsys