* Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
* ubs-engine is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef UBSE_ENV_UTIL_H
#define UBSE_ENV_UTIL_H
#include <algorithm>
#include <cctype>
#include <climits>
#include <cstdint>
#include <cstdlib>
#include <iterator>
#include <string>
namespace ubse::utils {
template <typename T>
class UbseEnvUtil {
public:
static bool Parse(const std::string& value, T& out) = delete;
};
template <>
class UbseEnvUtil<std::string> {
public:
static bool Parse(const std::string& value, std::string& out)
{
static constexpr size_t MAX_LENGTH = 1024;
if (value.length() > MAX_LENGTH) {
return false;
}
out = value;
return true;
}
};
template <>
class UbseEnvUtil<bool> {
public:
static bool Parse(const std::string& value, bool& out)
{
std::string lower;
lower.reserve(value.size());
std::transform(value.begin(), value.end(), std::back_inserter(lower), [](char c) { return std::tolower(c); });
if (lower == "true" || lower == "1" || lower == "yes") {
out = true;
return true;
}
if (lower == "false" || lower == "0" || lower == "no") {
out = false;
return true;
}
return false;
}
};
template <>
class UbseEnvUtil<int16_t> {
public:
static bool Parse(const std::string& value, int16_t& out)
{
try {
size_t end = 0;
const long parsed = std::stol(value, &end, 10);
const bool hasExtraChars = (end != value.size());
bool hasLeadingWhitespace = false;
if (!value.empty()) {
const size_t firstNonSpace = value.find_first_not_of(" \t");
hasLeadingWhitespace = (firstNonSpace != 0 && end > 0);
}
const bool isInvalid = (end == 0) ||
hasExtraChars ||
hasLeadingWhitespace ||
(parsed < SHRT_MIN) ||
(parsed > SHRT_MAX);
if (!isInvalid) {
out = static_cast<int16_t>(parsed);
return true;
}
} catch (...) {
return false;
}
return false;
}
};
* 安全获取环境变量,解析失败时使用默认值。
* @tparam T 目标类型,需提供UbseEnvUtil特化
* @param name 环境变量名称
* @param defaultVal 默认值
* @return T 解析结果,解析失败时使用默认值。
*/
template <typename T>
T GetEnv(const char* name, const T& defaultVal = T{})
{
if (const auto envValue = std::getenv(name)) {
T parsed;
if (UbseEnvUtil<T>::Parse(envValue, parsed)) {
return parsed;
}
}
return defaultVal;
}
}
#endif