fix(env_var): improve bounds checking
This commit is contained in:
@@ -3,6 +3,7 @@
|
|||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <limits>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
|
||||||
@@ -70,31 +71,50 @@ class EnvVarRegistry {
|
|||||||
}; \
|
}; \
|
||||||
}
|
}
|
||||||
|
|
||||||
#define DEFINE_ENV_VAR_INT(TYPE, name, DEFAULT_VALUE) \
|
#define DEFINE_ENV_VAR_INT(TYPE, name, DEFAULT_VALUE) \
|
||||||
namespace EnvVars { \
|
namespace EnvVars { \
|
||||||
struct name { \
|
struct name { \
|
||||||
static constexpr TYPE DEFAULT = DEFAULT_VALUE; \
|
static constexpr TYPE DEFAULT = DEFAULT_VALUE; \
|
||||||
static constexpr char const* NAME = #name; \
|
static constexpr char const* NAME = #name; \
|
||||||
static TYPE GET() { \
|
static TYPE GET() { \
|
||||||
auto c = std::getenv(#name); \
|
constexpr auto lower_bound = std::numeric_limits<TYPE>::min(); \
|
||||||
if (c) { \
|
constexpr auto upper_bound = std::numeric_limits<TYPE>::max(); \
|
||||||
if (std::strlen(c) > 0) { \
|
auto c = std::getenv(#name); \
|
||||||
try { \
|
if (c) { \
|
||||||
if constexpr (std::is_unsigned_v<TYPE>) { \
|
if (std::strlen(c) > 0) { \
|
||||||
TYPE x = static_cast<TYPE>(std::stoull(c)); \
|
try { \
|
||||||
return x; \
|
if constexpr (std::is_unsigned_v<TYPE>) { \
|
||||||
} else { \
|
const char* p = c; \
|
||||||
TYPE x = static_cast<TYPE>(std::stoll(c)); \
|
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') { \
|
||||||
return x; \
|
++p; \
|
||||||
} \
|
} \
|
||||||
} catch (...) {} \
|
if (*p == '-') { \
|
||||||
} \
|
return lower_bound; \
|
||||||
} \
|
} \
|
||||||
return DEFAULT_VALUE; \
|
auto x = std::stoull(c); \
|
||||||
} \
|
if (x > upper_bound) { \
|
||||||
static inline ::cpputils::env_var::EnvVarRegistry::EnvVarAutoRegister \
|
return upper_bound; \
|
||||||
_env_register{#name, DEFAULT_VALUE}; \
|
} else { \
|
||||||
}; \
|
return x; \
|
||||||
|
} \
|
||||||
|
} else { \
|
||||||
|
auto x = std::stoll(c); \
|
||||||
|
if (x > upper_bound) { \
|
||||||
|
return upper_bound; \
|
||||||
|
} else if (x < lower_bound) { \
|
||||||
|
return lower_bound; \
|
||||||
|
} else { \
|
||||||
|
return x; \
|
||||||
|
} \
|
||||||
|
} \
|
||||||
|
} catch (...) {} \
|
||||||
|
} \
|
||||||
|
} \
|
||||||
|
return DEFAULT_VALUE; \
|
||||||
|
} \
|
||||||
|
static inline ::cpputils::env_var::EnvVarRegistry::EnvVarAutoRegister \
|
||||||
|
_env_register{#name, DEFAULT_VALUE}; \
|
||||||
|
}; \
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace env_var
|
} // namespace env_var
|
||||||
|
|||||||
Reference in New Issue
Block a user