AsmGrader 0.0.0
Loading...
Searching...
No Matches
time.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "common/expected.hpp"
4#include "logging.hpp"
5
6#include <array>
7#include <cerrno>
8#include <chrono>
9#include <cstddef>
10#include <ctime>
11#include <string>
12#include <system_error>
13
14namespace asmgrader {
15
16__attribute__((format(strftime, 2, 0))) // help the compiler check `format` for validity
17inline Expected<std::string>
18to_localtime_string(std::chrono::system_clock::time_point time_point, const char* format = "%Y-%m-%d %H:%M:%S") {
19
20 // Convert to time_t (seconds since epoch)
21 std::time_t time = std::chrono::system_clock::to_time_t(time_point);
22
23 // Convert to broken-down local time
24 std::tm tm_buf{};
25
26 if (localtime_r(&time, &tm_buf) != &tm_buf) {
27 auto err = errno;
28 LOG_WARN("localtime_r failed to convert to local time: ", get_err_msg(err));
29 return std::error_code{err, std::generic_category()};
30 }
31
32 constexpr std::size_t BUF_SZ = 1024;
33 std::array<char, BUF_SZ> buf{};
34
35#pragma GCC diagnostic push
36#pragma GCC diagnostic ignored "-Wformat-nonliteral"
37 // Format with strftime
38 if (std::size_t num_chars = std::strftime(buf.data(), buf.size(), format, &tm_buf)) {
39 return std::string{buf.begin(), num_chars};
40 }
41#pragma GCC diagnostic pop
42
43 auto err = errno;
44 LOG_WARN("strftime failed to format time point ", get_err_msg(err));
45 return std::error_code{err, std::generic_category()};
46}
47
48} // namespace asmgrader
std::variant wrapper for a partial implementation of C++23's expected type
Definition expected.hpp:34
#define LOG_WARN(...)
Definition logging.hpp:46
Definition asm_buffer.hpp:19
std::string get_err_msg()
Obtain Linux error (i.e., errno) message via libc functions.
Definition logging.hpp:97
__attribute__((format(strftime, 2, 0))) inline Expected< std
Definition time.hpp:16