-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathgetenv_util.hpp
More file actions
98 lines (80 loc) · 1.78 KB
/
getenv_util.hpp
File metadata and controls
98 lines (80 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
// Copyright (c) 2022-2026 Ben Ashbaugh
//
// SPDX-License-Identifier: MIT
*/
#pragma once
#include <stdlib.h>
#include <string.h>
#include <string>
#if defined(_WIN32)
#include <windows.h>
#define GETENV( _name, _value ) _dupenv_s( &_value, NULL, _name )
#define FREEENV( _value ) free( _value )
#else
#define GETENV( _name, _value ) _value = getenv(_name)
#define FREEENV( _value ) (void)_value
#endif
static inline bool getControlFromEnvironment(
const char* name,
void* pValue,
size_t size )
{
char* envVal = NULL;
GETENV( name, envVal );
if( envVal != NULL )
{
if( size == sizeof(unsigned int) )
{
unsigned int* puVal = (unsigned int*)pValue;
*puVal = atoi(envVal);
}
else if( strlen(envVal) < size )
{
char* pStr = (char*)pValue;
strcpy( pStr, envVal );
}
FREEENV( envVal );
return true;
}
return false;
}
template <class T>
static bool getControl(
const char* name,
T& value )
{
unsigned int readValue = 0;
bool success = getControlFromEnvironment( name, &readValue, sizeof(readValue) );
if( success )
{
value = readValue;
}
return success;
}
template <>
bool getControl<bool>(
const char* name,
bool& value )
{
unsigned int readValue = 0;
bool success = getControlFromEnvironment( name, &readValue, sizeof(readValue) );
if( success )
{
value = ( readValue != 0 );
}
return success;
}
template <>
bool getControl<std::string>(
const char* name,
std::string& value )
{
char readValue[256] = "";
bool success = getControlFromEnvironment( name, readValue, sizeof(readValue) );
if( success )
{
value = readValue;
}
return success;
}