Modern C++ Kafka API
Timestamp.h
1 #pragma once
2 
3 #include <kafka/Project.h>
4 
5 #include <librdkafka/rdkafka.h>
6 
7 #include <cassert>
8 #include <chrono>
9 #include <iomanip>
10 #include <sstream>
11 #include <string>
12 #include <time.h>
13 
14 
15 namespace KAFKA_API {
16 
20 struct Timestamp
21 {
22  using Value = std::int64_t;
23 
24  enum class Type { NotAvailable, CreateTime, LogAppendTime };
25 
29  Value msSinceEpoch;
30 
34  Type type;
35 
36  explicit Timestamp(Value v = 0, Type t = Type::NotAvailable): msSinceEpoch(v), type(t) {}
37  Timestamp(Value v, rd_kafka_timestamp_type_t t): Timestamp(v, convertType(t)) {}
38 
39  static Type convertType(rd_kafka_timestamp_type_t tstype)
40  {
41  return (tstype == RD_KAFKA_TIMESTAMP_CREATE_TIME) ? Type::CreateTime :
42  (tstype == RD_KAFKA_TIMESTAMP_LOG_APPEND_TIME ? Type::LogAppendTime : Type::NotAvailable);
43  }
44 
45  operator std::chrono::time_point<std::chrono::system_clock>() const // NOLINT
46  {
47  return std::chrono::time_point<std::chrono::system_clock>(std::chrono::milliseconds(msSinceEpoch));
48  }
49 
50  static std::string toString(Type t)
51  {
52  switch (t)
53  {
54  case Type::CreateTime:
55  return "CreateTime";
56  case Type::LogAppendTime:
57  return "LogAppendTime";
58  default:
59  assert(t == Type::NotAvailable);
60  return "";
61  }
62  }
63 
64  static std::string toString(Value v)
65  {
66  auto ms = std::chrono::milliseconds(v);
67  auto timepoint = std::chrono::time_point<std::chrono::system_clock>(ms);
68  const std::time_t time = std::chrono::system_clock::to_time_t(timepoint);
69  std::ostringstream oss;
70  std::tm tmBuf = {};
71 #if !defined(WIN32)
72  oss << std::put_time(localtime_r(&time, &tmBuf), "%F %T") << "." << std::setfill('0') << std::setw(3) << (v % 1000);
73 #else
74  localtime_s(&tmBuf, &time);
75  oss << std::put_time(&tmBuf, "%F %T") << "." << std::setfill('0') << std::setw(3) << (v % 1000);
76 #endif
77  return oss.str();
78  }
79 
83  std::string toString() const
84  {
85  auto typeString = toString(type);
86  auto timeString = toString(msSinceEpoch);
87  return typeString.empty() ? timeString : (typeString + "[" + timeString + "]");
88  }
89 };
90 
91 } // end of KAFKA_API
92 
The time point together with the type.
Definition: Timestamp.h:21
Type type
The type shows what the msSinceEpoch means (CreateTime or LogAppendTime).
Definition: Timestamp.h:34
std::string toString() const
Obtains explanatory string.
Definition: Timestamp.h:83
Value msSinceEpoch
The milliseconds since epoch.
Definition: Timestamp.h:29