OdbDesign
OdbDesign ODB++ Parser - C++ library, gRPC/REST server, CLI, tests
 
Loading...
Searching...
No Matches
CrossPlatform.cpp
Go to the documentation of this file.
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
12namespace Utils
13{
14 std::mutex localtimeMutex;
15
16 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 std::lock_guard lock(localtimeMutex);
25 if (nullptr != localtime_r(time, &tmOut))
26 {
27 return true;
28 }
29 return false;
30 }
31 #else
32 return false;
33 #endif
34 }
35
36 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 auto val = std::getenv(env_var);
55 if (val != nullptr)
56 {
57 envValueOut = val;
58 return true;
59 }
60
61 }
62 #endif
63
64 return false;
65 }
66
67 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 char szTempName[L_tmpnam]{ 0 };
82 if (nullptr != std::tmpnam(szTempName))
83 {
84 tempNameOut = szTempName;
85 return true;
86 }
87 }
88 #endif
89
90 return false;
91 }
92}
static bool tmpnam_safe(std::string &tempNameOut)
static bool getenv_safe(const char *env_var, std::string &envValueOut)
static bool localtime_safe(const std::time_t *time, struct std::tm &tmOut)
std::mutex localtimeMutex