Line data Source code
1 : #include "CrossPlatform.h"
2 : #include "macros.h"
3 : #include <ctime>
4 : #include <cstdlib>
5 : #include <stdlib.h>
6 : #include <string>
7 : #include <time.h>
8 : #include <mutex>
9 : #include <cstdio>
10 : #include <ctime>
11 :
12 : namespace Utils
13 : {
14 : std::mutex localtimeMutex;
15 :
16 0 : bool CrossPlatform::localtime_safe(const std::time_t* time, struct std::tm& tmOut)
17 : {
18 : #if (IS_WINDOWS)
19 : {
20 : return (0 == localtime_s(&tmOut, time));
21 : }
22 : #elif (IS_LINUX || IS_APPLE)
23 : {
24 0 : std::lock_guard lock(localtimeMutex);
25 0 : if (nullptr != localtime_r(time, &tmOut))
26 : {
27 0 : return true;
28 : }
29 0 : return false;
30 0 : }
31 : #else
32 : return false;
33 : #endif
34 : }
35 :
36 138 : bool CrossPlatform::getenv_safe(const char* env_var, std::string& envValueOut)
37 : {
38 : #if (IS_WINDOWS)
39 : {
40 : char* envValue = nullptr;
41 : size_t len = 0;
42 : if (0 == _dupenv_s(&envValue, &len, env_var))
43 : {
44 : if (envValue != nullptr && len > 0)
45 : {
46 : envValueOut = envValue;
47 : free(envValue);
48 : return true;
49 : }
50 : }
51 : }
52 : #elif (IS_LINUX || IS_APPLE)
53 : {
54 138 : auto val = std::getenv(env_var);
55 138 : if (val != nullptr)
56 : {
57 137 : envValueOut = val;
58 137 : return true;
59 : }
60 :
61 : }
62 : #endif
63 :
64 1 : return false;
65 : }
66 :
67 2 : bool CrossPlatform::tmpnam_safe(std::string& tempNameOut)
68 : {
69 : #if (IS_WINDOWS)
70 : {
71 : char szTempName[L_tmpnam_s];
72 : if (0 == tmpnam_s(szTempName, L_tmpnam_s))
73 : {
74 : tempNameOut = szTempName;
75 : return true;
76 : }
77 : }
78 : #elif (IS_LINUX || IS_APPLE)
79 : {
80 : // mkstemp
81 2 : char szTempName[L_tmpnam]{ 0 };
82 2 : if (nullptr != std::tmpnam(szTempName))
83 : {
84 2 : tempNameOut = szTempName;
85 2 : return true;
86 : }
87 : }
88 : #endif
89 :
90 0 : return false;
91 : }
92 : }
|