2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file walltime_func.h Functionality related to the time of the clock on your wall. */
10 #ifndef WALLTIME_FUNC_H
11 #define WALLTIME_FUNC_H
15 /** Helper for safely converting a std::time_t to a local time std::tm using localtime_s. */
16 struct LocalTimeToStruct
{
17 static inline std::tm
ToTimeStruct(std::time_t time_since_epoch
)
21 /* Windows has swapped the parameters around for localtime_s. */
22 localtime_s(&time
, &time_since_epoch
);
24 localtime_r(&time_since_epoch
, &time
);
30 /** Helper for safely converting a std::time_t to a UTC time std::tm using gmtime_s. */
31 struct UTCTimeToStruct
{
32 static inline std::tm
ToTimeStruct(std::time_t time_since_epoch
)
36 /* Windows has swapped the parameters around for gmtime_s. */
37 gmtime_s(&time
, &time_since_epoch
);
39 gmtime_r(&time_since_epoch
, &time
);
46 * Container for wall clock time related functionality not directly provided by C++.
47 * @tparam T The type of the time-to-struct implementation class.
52 * Format the current time with the given strftime format specifiers.
53 * @param buffer The buffer to write the time string to.
54 * @param last The last element in the buffer.
55 * @param format The format according to strftime format specifiers.
56 * @return The number of characters that were written to the buffer.
58 static inline size_t Format(char *buffer
, const char *last
, const char *format
) NOACCESS(2) WARN_TIME_FORMAT(3)
60 std::tm time_struct
= T::ToTimeStruct(time(nullptr));
62 /* GCC bug #39438; unlike for printf where the appropriate attribute prevent the
63 * "format non literal" warning, that does not happen for strftime. Even though
64 * format warnings will be created for invalid strftime formats. */
65 #pragma GCC diagnostic push
66 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 return strftime(buffer
, last
- buffer
, format
, &time_struct
);
70 #pragma GCC diagnostic pop
75 /** Wall clock time functionality using the local time zone. */
76 using LocalTime
= Time
<LocalTimeToStruct
>;
77 /** Wall clock time functionality using the UTC time zone. */
78 using UTCTime
= Time
<UTCTimeToStruct
>;