From fb4a9b7ededc5bc49667c4f3aa57471f91de8957 Mon Sep 17 00:00:00 2001 From: Sam McCall Date: Tue, 24 Oct 2017 08:30:19 +0000 Subject: Support formatv of TimePoint with strftime-style formats. Summary: Support formatv of TimePoint with strftime-style formats. Extensions for millis/micros/nanos are added. Inital use case is HH:MM:SS.MMM timestamps in clangd logs. Reviewers: bkramer, ilya-biryukov Subscribers: labath, llvm-commits Differential Revision: https://reviews.llvm.org/D38992 llvm-svn: 316419 --- llvm/lib/Support/Chrono.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) (limited to 'llvm/lib/Support/Chrono.cpp') diff --git a/llvm/lib/Support/Chrono.cpp b/llvm/lib/Support/Chrono.cpp index daccaf1fc10..a39b485bd13 100644 --- a/llvm/lib/Support/Chrono.cpp +++ b/llvm/lib/Support/Chrono.cpp @@ -51,4 +51,44 @@ raw_ostream &operator<<(raw_ostream &OS, TimePoint<> TP) { .count())); } +void format_provider>::format(const TimePoint<> &T, raw_ostream &OS, + StringRef Style) { + using namespace std::chrono; + TimePoint Truncated = time_point_cast(T); + auto Fractional = T - Truncated; + struct tm LT = getStructTM(Truncated); + // Handle extensions first. strftime mangles unknown %x on some platforms. + if (Style.empty()) Style = "%Y-%m-%d %H:%M:%S.%N"; + std::string Format; + raw_string_ostream FStream(Format); + for (unsigned I = 0; I < Style.size(); ++I) { + if (Style[I] == '%' && Style.size() > I + 1) switch (Style[I + 1]) { + case 'L': // Milliseconds, from Ruby. + FStream << llvm::format( + "%.3lu", duration_cast(Fractional).count()); + ++I; + continue; + case 'f': // Microseconds, from Python. + FStream << llvm::format( + "%.6lu", duration_cast(Fractional).count()); + ++I; + continue; + case 'N': // Nanoseconds, from date(1). + FStream << llvm::format( + "%.6lu", duration_cast(Fractional).count()); + ++I; + continue; + case '%': // Consume %%, so %%f parses as (%%)f not %(%f) + FStream << "%%"; + ++I; + continue; + } + FStream << Style[I]; + } + FStream.flush(); + char Buffer[256]; // Should be enough for anywhen. + size_t Len = strftime(Buffer, sizeof(Buffer), Format.c_str(), <); + OS << (Len ? Buffer : "BAD-DATE-FORMAT"); +} + } // namespace llvm -- cgit v1.2.3