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
diff --git a/llvm/lib/Support/Chrono.cpp b/llvm/lib/Support/Chrono.cpp
index daccaf1..a39b485 100644
--- a/llvm/lib/Support/Chrono.cpp
+++ b/llvm/lib/Support/Chrono.cpp
@@ -51,4 +51,44 @@
.count()));
}
+void format_provider<TimePoint<>>::format(const TimePoint<> &T, raw_ostream &OS,
+ StringRef Style) {
+ using namespace std::chrono;
+ TimePoint<seconds> Truncated = time_point_cast<seconds>(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<milliseconds>(Fractional).count());
+ ++I;
+ continue;
+ case 'f': // Microseconds, from Python.
+ FStream << llvm::format(
+ "%.6lu", duration_cast<microseconds>(Fractional).count());
+ ++I;
+ continue;
+ case 'N': // Nanoseconds, from date(1).
+ FStream << llvm::format(
+ "%.6lu", duration_cast<nanoseconds>(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