/**
* Copyright (c) 2016 by Contributors
*/
#ifndef PS_INTERNAL_ENV_H_
#define PS_INTERNAL_ENV_H_
#include <cstdlib>
#include <unordered_map>
#include <memory>
#include <string>
namespace ps {
/**
* \brief Environment configurations
*/
class Environment {
public:
/** 返回单例 */
/**
* \brief return the singleton instance
*/
static inline Environment* Get() {
return _GetSharedRef(nullptr).get();
}
/** 返回单例共享引用 */
/**
* \brief return a shared ptr of the singleton instance
*/
static inline std::shared_ptr<Environment> _GetSharedRef() {
return _GetSharedRef(nullptr);
}
/** 一次创建单例类 */
/**
* \brief initialize the environment
* \param envs key-value environment variables
* \return the initialized singleton instance
*/
static inline Environment* Init(const std::unordered_map<std::string, std::string>& envs) {
Environment* env = _GetSharedRef(&envs).get();
env->kvs = envs;
return env;
}
/** 检索环境变量值 */
/**
* \brief find the env value.
* User-defined env vars first. If not found, check system's environment
* \param k the environment key
* \return the related environment value, nullptr when not found
*/
const char* find(const char* k) {
std::string key(k);
return kvs.find(key) == kvs.end() ? getenv(k) : kvs[key].c_str();
}
private:
/** 禁止外部创建和隐式类型转换 */
explicit Environment(const std::unordered_map<std::string, std::string>* envs) {
if (envs) kvs = *envs;
}
/** 创建单例或获取单例共享引用 */
static std::shared_ptr<Environment> _GetSharedRef(
const std::unordered_map<std::string, std::string>* envs) {
static std::shared_ptr<Environment> inst_ptr(new Environment(envs));
return inst_ptr;
}
std::unordered_map<std::string, std::string> kvs;
};
} // namespace ps
#endif // PS_INTERNAL_ENV_H_
ps-lite源码分析: include/ps/internal/env.h
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- /*** Copyright (c) 2015 by Contributors*/#ifndef PS_INTE...
- /*** Copyright (c) 2015 by Contributors*/#ifndef PS_BASE...
- 文章也同时在个人博客 http://kimihe.com/[http://kimihe.com/2018/06/0...