Common: Add utility function that wraps localtime_s() or localtime_t().

This commit is contained in:
Admiral H. Curtiss 2024-02-18 04:40:25 +01:00
parent 982ad93355
commit 52410813f2
No known key found for this signature in database
GPG Key ID: F051B4C4044F33FB
4 changed files with 41 additions and 0 deletions

View File

@ -138,6 +138,8 @@ add_library(common
Thread.h
Timer.cpp
Timer.h
TimeUtil.cpp
TimeUtil.h
TraversalClient.cpp
TraversalClient.h
TraversalProto.h

View File

@ -0,0 +1,24 @@
// Copyright 2024 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "Common/TimeUtil.h"
#include <ctime>
#include <optional>
namespace Common
{
std::optional<std::tm> Localtime(std::time_t time)
{
std::tm local_time;
#ifdef _MSC_VER
if (localtime_s(&local_time, &time) != 0)
return std::nullopt;
#else
std::tm* result = localtime_r(&time, &local_time);
if (result != &local_time)
return std::nullopt;
#endif
return local_time;
}
} // Namespace Common

View File

@ -0,0 +1,13 @@
// Copyright 2024 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <ctime>
#include <optional>
namespace Common
{
// Threadsafe and error-checking variant of std::localtime()
std::optional<std::tm> Localtime(std::time_t time);
} // Namespace Common

View File

@ -161,6 +161,7 @@
<ClInclude Include="Common\SymbolDB.h" />
<ClInclude Include="Common\Thread.h" />
<ClInclude Include="Common\Timer.h" />
<ClInclude Include="Common\TimeUtil.h" />
<ClInclude Include="Common\TraversalClient.h" />
<ClInclude Include="Common\TraversalProto.h" />
<ClInclude Include="Common\TypeUtils.h" />
@ -832,6 +833,7 @@
<ClCompile Include="Common\SymbolDB.cpp" />
<ClCompile Include="Common\Thread.cpp" />
<ClCompile Include="Common\Timer.cpp" />
<ClCompile Include="Common\TimeUtil.cpp" />
<ClCompile Include="Common\TraversalClient.cpp" />
<ClCompile Include="Common\UPnP.cpp" />
<ClCompile Include="Common\WindowsRegistry.cpp" />