userver: userver/utils/time_of_day.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
time_of_day.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/time_of_day.hpp
4/// @brief @copybrief utils::datetime::TimeOfDay
5
6#include <algorithm>
7#include <array>
8#include <chrono>
9#include <string_view>
10#include <type_traits>
11#include <vector>
12
13#include <fmt/format.h>
14
15#include <userver/compiler/impl/three_way_comparison.hpp>
16#include <userver/utils/fmt_compat.hpp>
17
18USERVER_NAMESPACE_BEGIN
19
20namespace logging {
21class LogHelper;
22}
23
24namespace utils::datetime {
25
26/// @ingroup userver_universal
27///
28/// @brief A simple implementation of a "time since midnight" datatype.
29///
30/// This type is time-zone ignorant.
31///
32/// Valid time range is from [00:00:00.0, 24:00:00.0)
33///
34/// Available construction:
35///
36/// from duration (since midnight, the value will be normalized, e.g. 25:00 will
37/// become 01:00, 24:00 will become 00:00)
38///
39/// from string representation HH:MM[:SS[.s]], accepted range is from 00:00 to
40/// 24:00
41///
42/// construction from int in form 1300 as a static member function
43///
44/// Accessors:
45///
46/// int Hours(); // hours since midnight
47/// int Minutes(); // minutes since midnight + Hours()
48/// int Seconds(); // seconds since midnight + Hours() + Minutes()
49/// int Subseconds(); // seconds fraction since
50/// midnight + Hours() + Minutes() + Seconds()
51///
52///
53/// Output:
54///
55/// LOG(xxx) << val
56///
57/// Formatting:
58///
59/// fmt::format("{}", val)
60///
61/// Default format for hours and minutes is HH:MM, for seconds HH:MM:SS, for
62/// subseconds HH:MM:SS.s with fractional part, but truncating trailing zeros.
63///
64/// Custom formatting:
65///
66/// fmt:format("{:%H%M%S}", val); // will output HHMMSS without separators
67///
68/// Format keys:
69/// %H 24-hour two-digit zero-padded hours
70/// %M two-digit zero-padded minutes
71/// %S two-digit zero-padded seconds
72/// %% literal %
73template <typename Duration>
74class TimeOfDay;
75
76template <typename Rep, typename Period>
77class TimeOfDay<std::chrono::duration<Rep, Period>> {
78public:
79 using DurationType = std::chrono::duration<Rep, Period>;
80
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);
86
87 //@{
88 /** @name Comparison operators */
89
90#ifdef USERVER_IMPL_HAS_THREE_WAY_COMPARISON
91 constexpr auto operator<=>(const TimeOfDay&) const = default;
92#else
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;
99#endif
100 //@}
101
102 //@{
103 /** @name Accessors */
104 /// @return Hours since midnight
105 constexpr std::chrono::hours Hours() const noexcept {
106 return std::chrono::duration_cast<std::chrono::hours>(since_midnight_);
107 }
108
109 /// @return Minutes since midnight + Hours
110 constexpr std::chrono::minutes Minutes() const noexcept;
111 /// @return Seconds since midnight + Hours + Minutes
112 constexpr std::chrono::seconds Seconds() const noexcept;
113 /// @return Fractional part of seconds since midnight + Hours + Minutes +
114 /// Seconds up to resolution
115 constexpr DurationType Subseconds() const noexcept;
116
117 /// @return Underlying duration representation
118 constexpr DurationType SinceMidnight() const noexcept;
119 //@}
120
121 /// Create time of day from integer representation, e.g.1330 => 13:30
122 constexpr static TimeOfDay FromHHMMInt(int);
123
124private:
125 DurationType since_midnight_{};
126};
127
128//@{
129/** @name Duration arithmetic */
130
131template <typename LDuration, typename RDuration>
132auto operator-(TimeOfDay<LDuration> lhs, TimeOfDay<RDuration> rhs) {
133 return lhs.SinceMidnight() - rhs.SinceMidnight();
134}
135
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};
139}
140
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};
144}
145//@}
146
147template <typename Duration>
148logging::LogHelper& operator<<(logging::LogHelper& lh, TimeOfDay<Duration> value) {
149 lh << fmt::to_string(value);
150 return lh;
151}
152
153namespace detail {
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});
157
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;
162}
163
164template <typename Ratio>
165inline constexpr std::size_t kDecimalPositions = 0;
166template <>
167inline constexpr std::size_t kDecimalPositions<std::milli> = 3;
168template <>
169inline constexpr std::size_t kDecimalPositions<std::micro> = 6;
170template <>
171inline constexpr const std::size_t kDecimalPositions<std::nano> = 9;
172
173constexpr std::intmax_t MissingDigits(std::size_t n) {
174 // As we support resolutions up to nano, all we need is up to 10^9
175 // clang-format off
176 constexpr std::intmax_t powers[]{
177 1,
178 10,
179 100,
180 1'000,
181 10'000,
182 100'000,
183 1'000'000,
184 10'000'000,
185 100'000'000,
186 1'000'000'000
187 };
188 // clang-format on
189
190 return powers[n];
191}
192
193template <typename Ratio>
194struct HasMinutes : std::false_type {};
195
196template <intmax_t Num, intmax_t Den>
197struct HasMinutes<std::ratio<Num, Den>> : std::integral_constant<bool, (Num <= 60LL)> {};
198
199template <typename Rep, typename Period>
200struct HasMinutes<std::chrono::duration<Rep, Period>> : HasMinutes<Period> {};
201
202template <typename Duration>
203struct HasMinutes<TimeOfDay<Duration>> : HasMinutes<Duration> {};
204
205template <typename T>
206constexpr inline bool kHasMinutes = HasMinutes<T>{};
207
208template <typename Ratio>
209struct HasSeconds : std::false_type {};
210
211template <intmax_t Num, intmax_t Den>
212struct HasSeconds<std::ratio<Num, Den>> : std::integral_constant<bool, (Num == 1)> {};
213
214template <typename Rep, typename Period>
215struct HasSeconds<std::chrono::duration<Rep, Period>> : HasSeconds<Period> {};
216
217template <typename Duration>
218struct HasSeconds<TimeOfDay<Duration>> : HasSeconds<Duration> {};
219
220template <typename T>
221constexpr inline bool kHasSeconds = HasSeconds<T>{};
222
223template <typename Ratio>
224struct HasSubseconds : std::false_type {};
225
226template <intmax_t Num, intmax_t Den>
227struct HasSubseconds<std::ratio<Num, Den>> : std::integral_constant<bool, (Den > 1)> {};
228
229template <typename Rep, typename Period>
230struct HasSubseconds<std::chrono::duration<Rep, Period>> : HasSubseconds<Period> {};
231
232template <typename Duration>
233struct HasSubseconds<TimeOfDay<Duration>> : HasSubseconds<Duration> {};
234
235template <typename T>
236constexpr inline bool kHasSubseconds = HasSubseconds<T>{};
237
238template <typename Rep, typename Period>
239class TimeOfDayParser {
240public:
241 using DurationType = std::chrono::duration<Rep, Period>;
242
243 constexpr DurationType operator()(std::string_view str) {
244 for (auto c : str) {
245 switch (c) {
246 case ':':
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);
251 break;
252 case '.':
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);
257 break;
258 default:
259 if (!std::isdigit(c))
260 throw std::runtime_error{
261 fmt::format("Unexpected character {} in TimeOfDay string `{}`", c, str)};
262 if (position_ == kOverflow) {
263 continue;
264 } else if (position_ == kSubseconds) {
265 if (digit_count_ >= kDecimalPositions<Period>) {
266 AssignCurrentPosition(str);
267 position_ = kOverflow;
268 continue;
269 }
270 } else if (digit_count_ >= 2) {
271 throw std::runtime_error{fmt::format("Too much digits in TimeOfDay string `{}`", str)};
272 }
273 ++digit_count_;
274 current_number_ = current_number_ * 10 + (c - '0');
275 break;
276 }
277 }
278 if (position_ == kHour)
279 throw std::runtime_error{fmt::format(
280 "Expected to have at least minutes after hours in "
281 "TimeOfDay string `{}`",
282 str
283 )};
284 AssignCurrentPosition(str);
285
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));
289 }
290 return NormalizeTimeOfDay<Rep, Period>(sum);
291 }
292
293private:
294 enum TimePart { kHour, kMinutes, kSeconds, kSubseconds, kOverflow };
295
296 void AssignCurrentPosition(std::string_view str) {
297 switch (position_) {
298 case kHour: {
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_};
304 break;
305 }
306 case kMinutes: {
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_};
313 break;
314 }
315 case kSeconds: {
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_};
322 break;
323 }
324 case kSubseconds: {
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>) {
329 // TODO check digit count and adjust if needed
330 if (digit_count_ < kDecimalPositions<Period>) {
331 current_number_ *= MissingDigits(kDecimalPositions<Period> - digit_count_);
332 }
333 subseconds_ = DurationType{current_number_};
334 }
335 break;
336 }
337 case kOverflow:
338 // Just ignore this
339 break;
340 }
341 current_number_ = 0;
342 digit_count_ = 0;
343 }
344
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};
350
351 std::size_t digit_count_{0};
352 std::size_t current_number_{0};
353};
354
355/// Format string used for format key `%H`, two-digit 24-hour left-padded by 0
356inline constexpr std::string_view kLongHourFormat = "{0:0>#2d}";
357/// Format string used for minutes, key `%M`, no variations
358inline constexpr std::string_view kMinutesFormat = "{1:0>#2d}";
359/// Format string used for seconds, key `%S`, no variations
360inline constexpr std::string_view kSecondsFormat = "{2:0>#2d}";
361/// Format string for subseconds, keys not yet assigned
362inline constexpr std::string_view kSubsecondsFormat = "{3}";
363
364template <typename Ratio>
365constexpr inline std::string_view kSubsecondsPreformat = ".0";
366template <>
367inline constexpr std::string_view kSubsecondsPreformat<std::milli> = ".{:0>#3d}";
368template <>
369inline constexpr std::string_view kSubsecondsPreformat<std::micro> = ".{:0>#6d}";
370template <>
371inline constexpr std::string_view kSubsecondsPreformat<std::nano> = ".{:0>#9d}";
372
373// Default format for formatting is HH:MM:SS
374template <typename Ratio>
375inline constexpr std::array<std::string_view, 5> kDefaultFormat{
376 {kLongHourFormat, ":", kMinutesFormat, ":", kSecondsFormat}};
377
378// Default format for formatting with minutes resolution is HH:MM
379template <>
380inline constexpr std::array<std::string_view, 3> kDefaultFormat<std::ratio<60, 1>>{
381 {kLongHourFormat, ":", kMinutesFormat}};
382
383// Default format for formatting with hours resolution is HH:MM
384template <>
385inline constexpr std::array<std::string_view, 3> kDefaultFormat<std::ratio<3600, 1>>{
386 {kLongHourFormat, ":", kMinutesFormat}};
387
388} // namespace detail
389
390template <typename Rep, typename Period>
391constexpr TimeOfDay<std::chrono::duration<Rep, Period>>::TimeOfDay(DurationType d) noexcept
392 : since_midnight_{detail::NormalizeTimeOfDay<Rep, Period>(d)} {}
393
394template <typename Rep, typename Period>
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)} {}
398
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)} {}
402
403#ifndef USERVER_IMPL_HAS_THREE_WAY_COMPARISON
404template <typename Rep, typename Period>
405constexpr bool TimeOfDay<std::chrono::duration<Rep, Period>>::operator==(const TimeOfDay& rhs) const {
407}
408
409template <typename Rep, typename Period>
410constexpr bool TimeOfDay<std::chrono::duration<Rep, Period>>::operator!=(const TimeOfDay& rhs) const {
411 return !(*this == rhs);
412}
413
414template <typename Rep, typename Period>
415constexpr bool TimeOfDay<std::chrono::duration<Rep, Period>>::operator<(const TimeOfDay& rhs) const {
417}
418
419template <typename Rep, typename Period>
420constexpr bool TimeOfDay<std::chrono::duration<Rep, Period>>::operator<=(const TimeOfDay& rhs) const {
422}
423
424template <typename Rep, typename Period>
425constexpr bool TimeOfDay<std::chrono::duration<Rep, Period>>::operator>(const TimeOfDay& rhs) const {
427}
428
429template <typename Rep, typename Period>
430constexpr bool TimeOfDay<std::chrono::duration<Rep, Period>>::operator>=(const TimeOfDay& rhs) const {
432}
433#endif
434
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());
440 } else {
441 return std::chrono::minutes{0};
442 }
443}
444
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_)
451 );
452 } else {
453 return std::chrono::seconds{0};
454 }
455}
456
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_);
462 } else {
463 return DurationType{0};
464 }
465}
466
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_;
471}
472
473template <typename Rep, typename Period>
474constexpr TimeOfDay<std::chrono::duration<Rep, Period>> TimeOfDay<std::chrono::duration<Rep, Period>>::FromHHMMInt(
475 int hh_mm
476) {
477 auto mm = hh_mm % 100;
478 if (mm >= 60)
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}};
481}
482
483} // namespace utils::datetime
484
485USERVER_NAMESPACE_END
486
487namespace fmt {
488
489template <typename Duration>
490class formatter<USERVER_NAMESPACE::utils::datetime::TimeOfDay<Duration>> {
491 /// Format string used for format key `%H`, two-digit 24-hour left-padded by 0
492 static constexpr auto kLongHourFormat = USERVER_NAMESPACE::utils::datetime::detail::kLongHourFormat;
493 /// Format string used for minutes, key `%M`, no variations
494 static constexpr auto kMinutesFormat = USERVER_NAMESPACE::utils::datetime::detail::kMinutesFormat;
495 /// Format string used for seconds, key `%S`, no variations
496 static constexpr auto kSecondsFormat = USERVER_NAMESPACE::utils::datetime::detail::kSecondsFormat;
497 /// Format string for subseconds, keys not yet assigned
498 /// for use in representation
499 static constexpr auto kSubsecondsFormat = USERVER_NAMESPACE::utils::datetime::detail::kSubsecondsFormat;
500
501 static constexpr auto kSubsecondsPreformat =
502 USERVER_NAMESPACE::utils::datetime::detail::kSubsecondsPreformat<typename Duration::period>;
503
504 static constexpr std::string_view kLiteralPercent = "%";
505
506 static constexpr auto kDefaultFormat =
507 USERVER_NAMESPACE::utils::datetime::detail::kDefaultFormat<typename Duration::period>;
508
509 constexpr std::string_view GetFormatForKey(char key) {
510 // TODO Check if time part already seen
511 switch (key) {
512 case 'H':
513 return kLongHourFormat;
514 case 'M':
515 return kMinutesFormat;
516 case 'S':
517 return kSecondsFormat;
518 default:
519 throw format_error{fmt::format("Unsupported format key {}", key)};
520 }
521 }
522
523public:
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;
529
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;
536 }
537 if (*it == '%') {
538 if (state == kPercent) {
539 PushBackFmt(kLiteralPercent);
540 state = kKey;
541 } else {
542 if (state == kChar && size > 0) {
543 PushBackFmt({begin, size});
544 }
545 state = kPercent;
546 }
547 } else {
548 if (state == kPercent) {
549 PushBackFmt(GetFormatForKey(*it));
550 state = kKey;
551 } else if (state == kKey) {
552 // start new literal
553 begin = it;
554 size = 1;
555 state = kChar;
556 } else {
557 ++size;
558 }
559 }
560 }
561 if (!custom_format) {
562 for (const auto fmt : kDefaultFormat) {
563 PushBackFmt(fmt);
564 }
565 }
566 if (state == kChar) {
567 if (size > 0) {
568 PushBackFmt({begin, size});
569 }
570 } else if (state == kPercent) {
571 throw format_error{"No format key after percent character"};
572 }
573 return it;
574 }
575
576 template <typename FormatContext>
577 constexpr auto format(const USERVER_NAMESPACE::utils::datetime::TimeOfDay<Duration>& value, FormatContext& ctx)
578 const {
579 auto hours = value.Hours().count();
580 auto mins = value.Minutes().count();
581 auto secs = value.Seconds().count();
582
583 auto ss = value.Subseconds().count();
584
585 // Number of decimal positions (min 1) + point + null terminator
586 constexpr std::size_t buffer_size =
587 std::max(
588 USERVER_NAMESPACE::utils::datetime::detail::kDecimalPositions<typename Duration::period>, std::size_t{1}
589 ) +
590 2;
591 char subseconds[buffer_size];
592 subseconds[0] = 0;
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_) {
597 // Truncate trailing zeros
598 for (auto last = buffer_size - 2; last > 0 && subseconds[last] == '0'; --last) subseconds[last] = 0;
599 }
600 }
601
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);
605 }
606 return res;
607 }
608
609private:
610 constexpr void PushBackFmt(std::string_view fmt) {
611 if (representation_size_ >= kRepresentationCapacity) {
612 throw format_error("Format string complexity exceeds TimeOfDay limits");
613 }
614 representation_[representation_size_++] = fmt;
615 }
616
617 // Enough for hours, minutes, seconds, text and some % literals.
618 static constexpr std::size_t kRepresentationCapacity = 10;
619
620 std::string_view representation_[kRepresentationCapacity]{};
621 std::size_t representation_size_{0};
622 bool truncate_trailing_subseconds_{true};
623};
624
625} // namespace fmt