From 1b8b02a4ab0aae072d0891301d1f9d5376e7912b Mon Sep 17 00:00:00 2001 From: Ed Tanous Date: Sun, 8 Jan 2023 12:35:35 -0800 Subject: Simplify datetime parsing This code as it stands pulls in the full datetime library from boost, including io, and a bunch of timezone code. The bmc doesn't make use of any of this, so we can rely on a much simplified version. Unfortunately for us, gcc still doesn't implement the c++20 std::chrono::parse[1]. There is a reference library available from [2] that backports the parse function to compilers that don't yet support it, and is the basis for the libc++ version. This commit opts to copy in the header as-written, under the assumption that we will never need to pull in new versions of this library, and will move to the std ersion as soon as it's available in the next gcc version. This commit simplifies things down to improve compile times and binary size. It saves ~22KB of compressed binary size, or about 3%. Tested: Unit tests pass. Pretty good coverage. [1] https://en.cppreference.com/w/cpp/chrono/parse [2] https://github.com/HowardHinnant/date/blob/master/include/date/date.h Signed-off-by: Ed Tanous Change-Id: I706b91cc3d9df3f32068125bc47ff0c374eb8d87 --- redfish-core/src/utils/time_utils.cpp | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 redfish-core/src/utils/time_utils.cpp (limited to 'redfish-core/src/utils') diff --git a/redfish-core/src/utils/time_utils.cpp b/redfish-core/src/utils/time_utils.cpp new file mode 100644 index 0000000000..f427ba64c4 --- /dev/null +++ b/redfish-core/src/utils/time_utils.cpp @@ -0,0 +1,44 @@ +#include "utils/time_utils.hpp" + +#include "utils/extern/date.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace redfish::time_utils +{ +using usSinceEpoch = std::chrono::duration; +std::optional dateStringToEpoch(std::string_view datetime) +{ + for (const char* format : std::to_array({"%FT%T%Ez", "%FT%TZ", "%FT%T"})) + { + // Parse using signed so we can detect negative dates + std::chrono::sys_time> date; + std::istringstream iss(std::string{datetime}); +#if __cpp_lib_chrono >= 201907L + namespace chrono_from_stream = std::chrono; +#else + namespace chrono_from_stream = date; +#endif + if (chrono_from_stream::from_stream(iss, format, date)) + { + if (date.time_since_epoch().count() < 0) + { + return std::nullopt; + } + if (iss.rdbuf()->in_avail() != 0) + { + // More information left at end of string. + continue; + } + return usSinceEpoch{date.time_since_epoch().count()}; + } + } + return std::nullopt; +} +} // namespace redfish::time_utils -- cgit v1.2.3