fix(env_var): improve bounds checking

This commit is contained in:
2026-02-01 11:09:08 +01:00
parent f49802a1a6
commit a29c946d26

View File

@@ -3,6 +3,7 @@
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <limits>
#include <string>
#include <unordered_map>
@@ -70,31 +71,50 @@ class EnvVarRegistry {
}; \
}
#define DEFINE_ENV_VAR_INT(TYPE, name, DEFAULT_VALUE) \
namespace EnvVars { \
struct name { \
static constexpr TYPE DEFAULT = DEFAULT_VALUE; \
static constexpr char const* NAME = #name; \
static TYPE GET() { \
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; \
} else { \
TYPE x = static_cast<TYPE>(std::stoll(c)); \
return x; \
} \
} catch (...) {} \
} \
} \
return DEFAULT_VALUE; \
} \
static inline ::cpputils::env_var::EnvVarRegistry::EnvVarAutoRegister \
_env_register{#name, DEFAULT_VALUE}; \
}; \
#define DEFINE_ENV_VAR_INT(TYPE, name, DEFAULT_VALUE) \
namespace EnvVars { \
struct name { \
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>) { \
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 { \
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