ps-lite源码分析: include/ps/internal/env.h

/**
 * Copyright (c) 2016 by Contributors
 */
#ifndef PS_INTERNAL_ENV_H_
#define PS_INTERNAL_ENV_H_
#include 
#include 
#include 
#include 
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 _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& 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* envs) {
    if (envs) kvs = *envs;
  }
 
 /** 创建单例或获取单例共享引用 */
  static std::shared_ptr _GetSharedRef(
      const std::unordered_map* envs) {
    static std::shared_ptr inst_ptr(new Environment(envs));
    return inst_ptr;
  }

  std::unordered_map kvs;
};

}  // namespace ps
#endif  // PS_INTERNAL_ENV_H_

你可能感兴趣的:(ps-lite源码分析: include/ps/internal/env.h)