OpenTTD Source  12.0-beta2
walltime_func.h
Go to the documentation of this file.
1 /*
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/>.
6  */
7 
10 #ifndef WALLTIME_FUNC_H
11 #define WALLTIME_FUNC_H
12 
13 #include <ctime>
14 
17  static inline std::tm ToTimeStruct(std::time_t time_since_epoch)
18  {
19  std::tm time = {};
20 #ifdef _WIN32
21  /* Windows has swapped the parameters around for localtime_s. */
22  localtime_s(&time, &time_since_epoch);
23 #else
24  localtime_r(&time_since_epoch, &time);
25 #endif
26  return time;
27  }
28 };
29 
32  static inline std::tm ToTimeStruct(std::time_t time_since_epoch)
33  {
34  std::tm time = {};
35 #ifdef _WIN32
36  /* Windows has swapped the parameters around for gmtime_s. */
37  gmtime_s(&time, &time_since_epoch);
38 #else
39  gmtime_r(&time_since_epoch, &time);
40 #endif
41  return time;
42  }
43 };
44 
49 template <typename T>
50 struct Time {
58  static inline size_t Format(char *buffer, const char *last, const char *format) NOACCESS(2) WARN_TIME_FORMAT(3)
59  {
60  std::tm time_struct = T::ToTimeStruct(time(nullptr));
61 #ifndef _MSC_VER
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"
67 #endif /* _MSC_VER */
68  return strftime(buffer, last - buffer, format, &time_struct);
69 #ifndef _MSC_VER
70 #pragma GCC diagnostic pop
71 #endif /* _MSC_VER */
72  }
73 };
74 
79 
80 #endif
Time
Container for wall clock time related functionality not directly provided by C++.
Definition: walltime_func.h:50
Time::Format
static size_t Format(char *buffer, const char *last, const char *format) NOACCESS(2) WARN_TIME_FORMAT(3)
Format the current time with the given strftime format specifiers.
Definition: walltime_func.h:58
LocalTimeToStruct
Helper for safely converting a std::time_t to a local time std::tm using localtime_s.
Definition: walltime_func.h:16
UTCTimeToStruct
Helper for safely converting a std::time_t to a UTC time std::tm using gmtime_s.
Definition: walltime_func.h:31