State: Make use of re-entrant variant of localtime

Makes this member function thread-safe. We can also unify the string
handling to make it easier to maintain.
This commit is contained in:
Lioncash 2024-01-23 15:22:37 -05:00
parent 1b3f61041a
commit 6a86b35e88

View File

@ -7,6 +7,7 @@
#include <atomic>
#include <condition_variable>
#include <filesystem>
#include <locale>
#include <map>
#include <memory>
#include <mutex>
@ -15,6 +16,7 @@
#include <utility>
#include <vector>
#include <fmt/chrono.h>
#include <fmt/format.h>
#include <lz4.h>
@ -278,21 +280,11 @@ static double GetSystemTimeAsDouble()
static std::string SystemTimeAsDoubleToString(double time)
{
// revert adjustments from GetSystemTimeAsDouble() to get a normal Unix timestamp again
time_t seconds = static_cast<time_t>(time) + DOUBLE_TIME_OFFSET;
errno = 0;
tm* local_time = localtime(&seconds);
if (errno != 0 || !local_time)
return "";
const time_t seconds = static_cast<time_t>(time) + DOUBLE_TIME_OFFSET;
const tm local_time = fmt::localtime(seconds);
#ifdef _WIN32
wchar_t tmp[32] = {};
wcsftime(tmp, std::size(tmp), L"%x %X", local_time);
return WStringToUTF8(tmp);
#else
char tmp[32] = {};
strftime(tmp, sizeof(tmp), "%x %X", local_time);
return tmp;
#endif
// fmt is locale agnostic by default, so explicitly use current locale.
return fmt::format(std::locale{""}, "{:%x %X}", local_time);
}
static std::string MakeStateFilename(int number);