Skip to content

Commit 4f2934c

Browse files
committed
increase fraction precision
1 parent 5918d30 commit 4f2934c

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

include/mgutility/chrono/parse.hpp

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
#include <chrono>
3535
#include <cstddef>
3636
#include <cstdint>
37+
#include <ratio>
3738
#include <stdexcept>
3839
#include <type_traits>
3940

@@ -82,6 +83,12 @@ constexpr int32_t abs(int32_t value) noexcept {
8283
return value >= 0 ? value : -value;
8384
}
8485

86+
// NOLINTNEXTLINE
87+
constexpr auto pow(int32_t base, int32_t exp) noexcept -> int32_t {
88+
// NOLINTNEXTLINE
89+
return exp < 0 ? 0 : exp == 0 ? 1 : base * pow(base, exp - 1);
90+
}
91+
8592
/**
8693
* @brief Checks if a value is within a given range.
8794
*
@@ -320,11 +327,17 @@ MGUTILITY_CNSTXPR auto parse_second(detail::tm &result, string_view date_str,
320327

321328
MGUTILITY_CNSTXPR auto parse_fraction(detail::tm &result, string_view date_str,
322329
uint32_t &next) -> std::errc {
323-
auto error = parse_integer(result.tm_ms, date_str, 3, next);
330+
int32_t digits = 0;
331+
while (next + digits < date_str.size() &&
332+
mgutility::detail::is_digit(date_str[next + digits]) && digits < 9) {
333+
++digits;
334+
}
335+
auto error = parse_integer(result.tm_ms, date_str, digits, next);
324336
if (error != std::errc{}) {
325337
return error;
326338
}
327-
error = check_range(result.tm_ms, 0U, 999U);
339+
result.tm_ms *= static_cast<uint32_t>(pow(10, 9 - digits));
340+
error = check_range(result.tm_ms, 0U, 999999999U);
328341
return error;
329342
}
330343

@@ -535,8 +548,7 @@ auto parse(typename Clock::time_point &time_point, string_view format,
535548
if (error != std::errc{}) {
536549
return std::make_error_code(error);
537550
}
538-
time_point = Clock::from_time_t(time_t);
539-
time_point += std::chrono::milliseconds(time_struct.tm_ms);
551+
time_point = std::chrono::time_point_cast<typename Clock::duration>(Clock::from_time_t(time_t) + std::chrono::nanoseconds{time_struct.tm_ms});
540552
return std::error_code{};
541553
}
542554

0 commit comments

Comments
 (0)