diff --git a/include/cpputils/env_var.h b/include/cpputils/env_var.h index 3427a31..b3a85c1 100644 --- a/include/cpputils/env_var.h +++ b/include/cpputils/env_var.h @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -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 x = static_cast(std::stoull(c)); \ - return x; \ - } else { \ - TYPE x = static_cast(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::min(); \ + constexpr auto upper_bound = std::numeric_limits::max(); \ + auto c = std::getenv(#name); \ + if (c) { \ + if (std::strlen(c) > 0) { \ + try { \ + if constexpr (std::is_unsigned_v) { \ + 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