fix(env_var): improve bounds checking
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
@@ -76,17 +77,36 @@ class EnvVarRegistry {
|
||||
static constexpr TYPE DEFAULT = DEFAULT_VALUE; \
|
||||
static constexpr char const* NAME = #name; \
|
||||
static TYPE GET() { \
|
||||
constexpr auto lower_bound = std::numeric_limits<TYPE>::min(); \
|
||||
constexpr auto upper_bound = std::numeric_limits<TYPE>::max(); \
|
||||
auto c = std::getenv(#name); \
|
||||
if (c) { \
|
||||
if (std::strlen(c) > 0) { \
|
||||
try { \
|
||||
if constexpr (std::is_unsigned_v<TYPE>) { \
|
||||
TYPE x = static_cast<TYPE>(std::stoull(c)); \
|
||||
return x; \
|
||||
const char* p = c; \
|
||||
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') { \
|
||||
++p; \
|
||||
} \
|
||||
if (*p == '-') { \
|
||||
return lower_bound; \
|
||||
} \
|
||||
auto x = std::stoull(c); \
|
||||
if (x > upper_bound) { \
|
||||
return upper_bound; \
|
||||
} else { \
|
||||
TYPE x = static_cast<TYPE>(std::stoll(c)); \
|
||||
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 (...) {} \
|
||||
} \
|
||||
} \
|
||||
|
||||
Reference in New Issue
Block a user