1 ////////////////////////////////////////////////////////////////////////////
3 // Copyright 2017 Realm Inc.
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
17 ////////////////////////////////////////////////////////////////////////////
19 #ifndef REALM_OS_UTIL_TIME_HPP
20 #define REALM_OS_UTIL_TIME_HPP
25 #include <system_error>
30 // Like std::localtime, but safe with reentrancy and multiple threads.
31 inline std::tm localtime(std::time_t time)
33 std::tm calendar_time;
35 // note that VC++'s localtime_s has a different signature from what C++11 specifies
36 auto error = localtime_s(&calendar_time, &time);
38 throw std::system_error(error, std::system_category());
40 auto result = localtime_r(&time, &calendar_time);
42 throw std::system_error(errno, std::system_category());
48 // Like std::put_time, but compatible with GCC 4.9.
49 inline std::string put_time(std::time_t time, const char *format)
51 std::tm calendar_time = localtime(time);
52 size_t estimated_length = std::strlen(format) + 1;
54 size_t formatted_length;
57 // Loop until the buffer is large enough to hold the string generated by `strftime`, growing the
58 // buffer by 8 characters whenever it is too small to hold the resulting string.
60 buffer.resize(estimated_length);
61 formatted_length = strftime(&buffer[0], buffer.size(), format, &calendar_time);
62 estimated_length += 8;
63 } while (formatted_length == 0);
65 buffer.resize(formatted_length);
72 #endif // REALM_OS_UTIL_TIME_HPP