uatools 1.0.0-pre2
 
Loading...
Searching...
No Matches
base.hpp
Go to the documentation of this file.
1
13
14#ifndef ESO_UATOOLS_PROTOCOL_BASE_BASE_HPP
15#define ESO_UATOOLS_PROTOCOL_BASE_BASE_HPP
16
17#include <array>
18#include <chrono>
19#include <cstdio>
20#include <ctime>
21#include <pthread.h>
22#include <string>
23
25
28 inline std::string ThreadName() {
29 std::array<char, 32> name{};
30 if (pthread_getname_np(pthread_self(), name.data(), name.size()) == 0) {
31 return std::string(name.data());
32 }
33 return {};
34 }
35
40 inline std::string IsoTimeNow(int frac_digits = 6) {
41 using namespace std::chrono;
42 const auto now = system_clock::now();
43 const auto secs = time_point_cast<seconds>(now);
44 const auto frac_us = duration_cast<microseconds>(now - secs).count();
45
46 const std::time_t tt = system_clock::to_time_t(now);
47 std::tm tm_buf{};
48 gmtime_r(&tt, &tm_buf);
49
50 char date_buf[32];
51 std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%dT%H:%M:%S", &tm_buf);
52
53 if (frac_digits <= 0) {
54 return std::string(date_buf);
55 }
56
57 // Clamp frac_digits to a sane range (microseconds = 6).
58 if (frac_digits > 6) {
59 frac_digits = 6;
60 }
61
62 // Scale microseconds down to the requested precision.
63 // frac_us is in [0, 1e6) so scaled fits in an int even at frac_digits=6.
64 int scaled = static_cast<int>(frac_us);
65 for (int i = 0; i < (6 - frac_digits); ++i) {
66 scaled /= 10;
67 }
68
69 char frac_buf[16];
70 std::snprintf(frac_buf, sizeof(frac_buf), ".%0*d", frac_digits, scaled);
71 return std::string(date_buf) + frac_buf;
72 }
73
74} // namespace eso::uatools::protocol::base
75
81#define UATLOC (::eso::uatools::protocol::base::IsoTimeNow(6) + ":" + \
82 std::string(__FILE__) + ":" + \
83 std::to_string(__LINE__) + ":" + \
84 std::string(__FUNCTION__) + ":" + \
85 ::eso::uatools::protocol::base::ThreadName())
86
87#endif // ESO_UATOOLS_PROTOCOL_BASE_BASE_HPP
Definition icomm_adapter_generic_v2.hpp:49
std::string IsoTimeNow(int frac_digits=6)
Return the current UTC time as an ISO 8601 string with frac_digits fractional second digits (default ...
Definition base.hpp:40
std::string ThreadName()
Return the current thread name (pthread_getname_np), or "" if unavailable. Bounded at 16 chars by the...
Definition base.hpp:28