13#include <fmt/format.h>
15#include <userver/compiler/impl/three_way_comparison.hpp>
16#include <userver/utils/fmt_compat.hpp>
18USERVER_NAMESPACE_BEGIN
73template <
typename Duration>
76template <
typename Rep,
typename Period>
77class TimeOfDay<std::chrono::duration<Rep, Period>> {
79 using DurationType = std::chrono::duration<Rep, Period>;
81 constexpr TimeOfDay()
noexcept =
default;
82 constexpr explicit TimeOfDay(DurationType)
noexcept;
83 template <
typename ORep,
typename OPeriod>
84 constexpr explicit TimeOfDay(std::chrono::duration<ORep, OPeriod>)
noexcept;
85 constexpr explicit TimeOfDay(std::string_view);
90#ifdef USERVER_IMPL_HAS_THREE_WAY_COMPARISON
91 constexpr auto operator<=>(
const TimeOfDay&)
const =
default;
93 constexpr bool operator==(
const TimeOfDay&)
const;
94 constexpr bool operator!=(
const TimeOfDay&)
const;
95 constexpr bool operator<(
const TimeOfDay&)
const;
96 constexpr bool operator<=(
const TimeOfDay&)
const;
97 constexpr bool operator>(
const TimeOfDay&)
const;
98 constexpr bool operator>=(
const TimeOfDay&)
const;
105 constexpr std::chrono::hours
Hours()
const noexcept {
106 return std::chrono::duration_cast<std::chrono::hours>(since_midnight_);
105 constexpr std::chrono::hours
Hours()
const noexcept {
…}
110 constexpr std::chrono::minutes
Minutes()
const noexcept;
112 constexpr std::chrono::seconds
Seconds()
const noexcept;
115 constexpr DurationType
Subseconds()
const noexcept;
125 DurationType since_midnight_{};
77class TimeOfDay<std::chrono::duration<Rep, Period>> {
…};
131template <
typename LDuration,
typename RDuration>
132auto operator-(TimeOfDay<LDuration> lhs, TimeOfDay<RDuration> rhs) {
133 return lhs.SinceMidnight() - rhs.SinceMidnight();
136template <
typename Duration,
typename Rep,
typename Period>
137TimeOfDay<Duration> operator+(TimeOfDay<Duration> lhs, std::chrono::duration<Rep, Period> rhs) {
138 return TimeOfDay<Duration>{lhs.SinceMidnight() + rhs};
141template <
typename Duration,
typename Rep,
typename Period>
142TimeOfDay<Duration> operator-(TimeOfDay<Duration> lhs, std::chrono::duration<Rep, Period> rhs) {
143 return TimeOfDay<Duration>{lhs.SinceMidnight() - rhs};
147template <
typename Duration>
148logging::LogHelper& operator<<(
logging::LogHelper& lh, TimeOfDay<Duration> value) {
149 lh << fmt::to_string(value);
154template <
typename Rep,
typename Period>
155inline constexpr std::chrono::duration<Rep, Period> kTwentyFourHours =
156 std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(std::chrono::hours{24});
158template <
typename Rep,
typename Period,
typename ORep = Rep,
typename OPeriod = Period>
159constexpr std::chrono::duration<Rep, Period> NormalizeTimeOfDay(std::chrono::duration<ORep, OPeriod> d) {
160 auto res = std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(d) % kTwentyFourHours<Rep, Period>;
161 return res.count() < 0 ? res + kTwentyFourHours<Rep, Period> : res;
164template <
typename Ratio>
165inline constexpr std::size_t kDecimalPositions = 0;
167inline constexpr std::size_t kDecimalPositions<std::milli> = 3;
169inline constexpr std::size_t kDecimalPositions<std::micro> = 6;
171inline constexpr const std::size_t kDecimalPositions<std::nano> = 9;
173constexpr std::intmax_t MissingDigits(std::size_t n) {
176 constexpr std::intmax_t powers[]{
193template <
typename Ratio>
194struct HasMinutes : std::false_type {};
196template <intmax_t Num, intmax_t Den>
197struct HasMinutes<std::ratio<Num, Den>> : std::integral_constant<
bool, (Num <= 60LL)> {};
199template <
typename Rep,
typename Period>
200struct HasMinutes<std::chrono::duration<Rep, Period>> : HasMinutes<Period> {};
202template <
typename Duration>
203struct HasMinutes<TimeOfDay<Duration>> : HasMinutes<Duration> {};
206constexpr inline bool kHasMinutes = HasMinutes<T>{};
208template <
typename Ratio>
209struct HasSeconds : std::false_type {};
211template <intmax_t Num, intmax_t Den>
212struct HasSeconds<std::ratio<Num, Den>> : std::integral_constant<
bool, (Num == 1)> {};
214template <
typename Rep,
typename Period>
215struct HasSeconds<std::chrono::duration<Rep, Period>> : HasSeconds<Period> {};
217template <
typename Duration>
218struct HasSeconds<TimeOfDay<Duration>> : HasSeconds<Duration> {};
221constexpr inline bool kHasSeconds = HasSeconds<T>{};
223template <
typename Ratio>
224struct HasSubseconds : std::false_type {};
226template <intmax_t Num, intmax_t Den>
227struct HasSubseconds<std::ratio<Num, Den>> : std::integral_constant<
bool, (Den > 1)> {};
229template <
typename Rep,
typename Period>
230struct HasSubseconds<std::chrono::duration<Rep, Period>> : HasSubseconds<Period> {};
232template <
typename Duration>
233struct HasSubseconds<TimeOfDay<Duration>> : HasSubseconds<Duration> {};
236constexpr inline bool kHasSubseconds = HasSubseconds<T>{};
238template <
typename Rep,
typename Period>
239class TimeOfDayParser {
241 using DurationType = std::chrono::duration<Rep, Period>;
243 constexpr DurationType operator()(std::string_view str) {
247 if (position_ >= kSeconds)
248 throw std::runtime_error{fmt::format(
"Extra colon in TimeOfDay string `{}`", str)};
249 AssignCurrentPosition(str);
250 position_ =
static_cast<TimePart>(position_ + 1);
253 if (position_ != kSeconds)
254 throw std::runtime_error{fmt::format(
"Unexpected decimal point in TimeOfDay string `{}`", str)};
255 AssignCurrentPosition(str);
256 position_ =
static_cast<TimePart>(position_ + 1);
259 if (!std::isdigit(c))
260 throw std::runtime_error{
261 fmt::format(
"Unexpected character {} in TimeOfDay string `{}`", c, str)};
262 if (position_ == kOverflow) {
264 }
else if (position_ == kSubseconds) {
265 if (digit_count_ >= kDecimalPositions<Period>) {
266 AssignCurrentPosition(str);
267 position_ = kOverflow;
270 }
else if (digit_count_ >= 2) {
271 throw std::runtime_error{fmt::format(
"Too much digits in TimeOfDay string `{}`", str)};
274 current_number_ = current_number_ * 10 + (c -
'0');
278 if (position_ == kHour)
279 throw std::runtime_error{fmt::format(
280 "Expected to have at least minutes after hours in "
281 "TimeOfDay string `{}`",
284 AssignCurrentPosition(str);
286 auto sum = hours_ + minutes_ + seconds_ + subseconds_;
287 if (sum > kTwentyFourHours<Rep, Period>) {
288 throw std::runtime_error(fmt::format(
"TimeOfDay value {} is out of range [00:00, 24:00)", str));
290 return NormalizeTimeOfDay<Rep, Period>(sum);
294 enum TimePart { kHour, kMinutes, kSeconds, kSubseconds, kOverflow };
296 void AssignCurrentPosition(std::string_view str) {
299 if (digit_count_ < 1)
300 throw std::runtime_error{fmt::format(
"Not enough digits for hours in TimeOfDay string `{}`", str)};
301 if (current_number_ > 24)
302 throw std::runtime_error{fmt::format(
"Invalid value for hours in TimeOfDay string `{}`", str)};
303 hours_ = std::chrono::hours{current_number_};
307 if (digit_count_ != 2)
308 throw std::runtime_error{
309 fmt::format(
"Not enough digits for minutes in TimeOfDay string `{}`", str)};
310 if (current_number_ > 59)
311 throw std::runtime_error{fmt::format(
"Invalid value for minutes in TimeOfDay string `{}`", str)};
312 minutes_ = std::chrono::minutes{current_number_};
316 if (digit_count_ != 2)
317 throw std::runtime_error{
318 fmt::format(
"Not enough digits for seconds in TimeOfDay string `{}`", str)};
319 if (current_number_ > 59)
320 throw std::runtime_error{fmt::format(
"Invalid value for seconds in TimeOfDay string `{}`", str)};
321 seconds_ = std::chrono::seconds{current_number_};
325 if (digit_count_ < 1)
326 throw std::runtime_error{
327 fmt::format(
"Not enough digits for subseconds in TimeOfDay string `{}`", str)};
328 if constexpr (kHasSubseconds<Period>) {
330 if (digit_count_ < kDecimalPositions<Period>) {
331 current_number_ *= MissingDigits(kDecimalPositions<Period> - digit_count_);
333 subseconds_ = DurationType{current_number_};
345 TimePart position_ = kHour;
346 std::chrono::hours hours_{0};
347 std::chrono::minutes minutes_{0};
348 std::chrono::seconds seconds_{0};
349 DurationType subseconds_{0};
351 std::size_t digit_count_{0};
352 std::size_t current_number_{0};
356inline constexpr std::string_view kLongHourFormat =
"{0:0>#2d}";
358inline constexpr std::string_view kMinutesFormat =
"{1:0>#2d}";
360inline constexpr std::string_view kSecondsFormat =
"{2:0>#2d}";
362inline constexpr std::string_view kSubsecondsFormat =
"{3}";
364template <
typename Ratio>
365constexpr inline std::string_view kSubsecondsPreformat =
".0";
367inline constexpr std::string_view kSubsecondsPreformat<std::milli> =
".{:0>#3d}";
369inline constexpr std::string_view kSubsecondsPreformat<std::micro> =
".{:0>#6d}";
371inline constexpr std::string_view kSubsecondsPreformat<std::nano> =
".{:0>#9d}";
374template <
typename Ratio>
375inline constexpr std::array<std::string_view, 5> kDefaultFormat{
376 {kLongHourFormat,
":", kMinutesFormat,
":", kSecondsFormat}};
380inline constexpr std::array<std::string_view, 3> kDefaultFormat<std::ratio<60, 1>>{
381 {kLongHourFormat,
":", kMinutesFormat}};
385inline constexpr std::array<std::string_view, 3> kDefaultFormat<std::ratio<3600, 1>>{
386 {kLongHourFormat,
":", kMinutesFormat}};
390template <
typename Rep,
typename Period>
391constexpr TimeOfDay<std::chrono::duration<Rep, Period>>::TimeOfDay(DurationType d)
noexcept
392 : since_midnight_{detail::NormalizeTimeOfDay<Rep, Period>(d)} {}
395template <
typename ORep,
typename OPeriod>
396constexpr TimeOfDay<std::chrono::duration<Rep, Period>>::TimeOfDay(std::chrono::duration<ORep, OPeriod> d)
noexcept
397 : since_midnight_{detail::NormalizeTimeOfDay<Rep, Period>(d)} {}
399template <
typename Rep,
typename Period>
400constexpr TimeOfDay<std::chrono::duration<Rep, Period>>::TimeOfDay(std::string_view str)
401 : since_midnight_{detail::TimeOfDayParser<Rep, Period>{}(str)} {}
403#ifndef USERVER_IMPL_HAS_THREE_WAY_COMPARISON
411 return !(*
this ==
rhs);
435template <
typename Rep,
typename Period>
436constexpr std::chrono::minutes TimeOfDay<std::chrono::duration<Rep, Period>>::
Minutes()
const noexcept {
437 if constexpr (detail::kHasMinutes<Period>) {
438 return std::chrono::duration_cast<std::chrono::minutes>(since_midnight_) -
439 std::chrono::duration_cast<std::chrono::minutes>(
Hours());
441 return std::chrono::minutes{0};
436constexpr std::chrono::minutes TimeOfDay<std::chrono::duration<Rep, Period>>::
Minutes()
const noexcept {
…}
445template <
typename Rep,
typename Period>
446constexpr std::chrono::seconds TimeOfDay<std::chrono::duration<Rep, Period>>::
Seconds()
const noexcept {
447 if constexpr (detail::kHasSeconds<Period>) {
448 return std::chrono::duration_cast<std::chrono::seconds>(since_midnight_) -
449 std::chrono::duration_cast<std::chrono::seconds>(
450 std::chrono::duration_cast<std::chrono::minutes>(since_midnight_)
453 return std::chrono::seconds{0};
446constexpr std::chrono::seconds TimeOfDay<std::chrono::duration<Rep, Period>>::
Seconds()
const noexcept {
…}
457template <
typename Rep,
typename Period>
458constexpr typename TimeOfDay<std::chrono::duration<Rep, Period>>::DurationType
459TimeOfDay<std::chrono::duration<Rep, Period>>::
Subseconds()
const noexcept {
460 if constexpr (detail::kHasSubseconds<Period>) {
461 return since_midnight_ - std::chrono::duration_cast<std::chrono::seconds>(since_midnight_);
463 return DurationType{0};
459TimeOfDay<std::chrono::duration<Rep, Period>>::
Subseconds()
const noexcept {
…}
467template <
typename Rep,
typename Period>
468constexpr typename TimeOfDay<std::chrono::duration<Rep, Period>>::DurationType
469TimeOfDay<std::chrono::duration<Rep, Period>>::
SinceMidnight()
const noexcept {
470 return since_midnight_;
473template <
typename Rep,
typename Period>
474constexpr TimeOfDay<std::chrono::duration<Rep, Period>> TimeOfDay<std::chrono::duration<Rep, Period>>::
FromHHMMInt(
477 auto mm = hh_mm % 100;
479 throw std::runtime_error{fmt::format(
"Invalid value for minutes {} in int representation {}", mm, hh_mm)};
480 return TimeOfDay{std::chrono::minutes{hh_mm / 100 * 60 + mm}};
474constexpr TimeOfDay<std::chrono::duration<Rep, Period>> TimeOfDay<std::chrono::duration<Rep, Period>>::
FromHHMMInt( {
…}
489template <
typename Duration>
492 static constexpr auto kLongHourFormat = USERVER_NAMESPACE::
utils::
datetime::detail::kLongHourFormat;
494 static constexpr auto kMinutesFormat = USERVER_NAMESPACE::
utils::
datetime::detail::kMinutesFormat;
496 static constexpr auto kSecondsFormat = USERVER_NAMESPACE::
utils::
datetime::detail::kSecondsFormat;
499 static constexpr auto kSubsecondsFormat = USERVER_NAMESPACE::
utils::
datetime::detail::kSubsecondsFormat;
501 static constexpr auto kSubsecondsPreformat =
502 USERVER_NAMESPACE::
utils::
datetime::detail::kSubsecondsPreformat<
typename Duration::period>;
504 static constexpr std::string_view kLiteralPercent =
"%";
506 static constexpr auto kDefaultFormat =
507 USERVER_NAMESPACE::
utils::
datetime::detail::kDefaultFormat<
typename Duration::period>;
509 constexpr std::string_view GetFormatForKey(
char key) {
513 return kLongHourFormat;
515 return kMinutesFormat;
517 return kSecondsFormat;
519 throw format_error{fmt::format(
"Unsupported format key {}", key)};
524 constexpr auto parse(format_parse_context& ctx) {
525 enum { kChar, kPercent, kKey } state = kChar;
526 const auto* it = ctx.begin();
527 const auto* end = ctx.end();
528 const auto* begin = it;
530 bool custom_format =
false;
531 std::size_t size = 0;
532 for (; it != end && *it !=
'}'; ++it) {
533 if (!custom_format) {
534 representation_size_ = 0;
535 custom_format =
true;
538 if (state == kPercent) {
539 PushBackFmt(kLiteralPercent);
542 if (state == kChar && size > 0) {
543 PushBackFmt({begin, size});
548 if (state == kPercent) {
549 PushBackFmt(GetFormatForKey(*it));
551 }
else if (state == kKey) {
561 if (!custom_format) {
562 for (
const auto fmt : kDefaultFormat) {
566 if (state == kChar) {
568 PushBackFmt({begin, size});
570 }
else if (state == kPercent) {
571 throw format_error{
"No format key after percent character"};
576 template <
typename FormatContext>
577 constexpr auto format(
const USERVER_NAMESPACE::
utils::
datetime::TimeOfDay<Duration>& value, FormatContext& ctx)
579 auto hours = value.Hours().count();
580 auto mins = value.Minutes().count();
581 auto secs = value.Seconds().count();
583 auto ss = value.Subseconds().count();
586 constexpr std::size_t buffer_size =
588 USERVER_NAMESPACE::
utils::
datetime::detail::kDecimalPositions<
typename Duration::period>, std::size_t{1}
591 char subseconds[buffer_size];
593 if (ss > 0 || !truncate_trailing_subseconds_) {
594 fmt::format_to(subseconds, kSubsecondsPreformat, ss);
595 subseconds[buffer_size - 1] = 0;
596 if (truncate_trailing_subseconds_) {
598 for (
auto last = buffer_size - 2; last > 0 && subseconds[last] ==
'0'; --last) subseconds[last] = 0;
602 auto res = ctx.out();
603 for (std::size_t i = 0; i < representation_size_; ++i) {
604 res = format_to(ctx.out(), fmt::runtime(representation_[i]), hours, mins, secs, subseconds);
610 constexpr void PushBackFmt(std::string_view fmt) {
611 if (representation_size_ >= kRepresentationCapacity) {
612 throw format_error(
"Format string complexity exceeds TimeOfDay limits");
614 representation_[representation_size_++] = fmt;
618 static constexpr std::size_t kRepresentationCapacity = 10;
620 std::string_view representation_[kRepresentationCapacity]{};
621 std::size_t representation_size_{0};
622 bool truncate_trailing_subseconds_{
true};