system.cpp 2.34 KB
Newer Older
Tim Moon's avatar
Tim Moon committed
1
/*************************************************************************
2
 * Copyright (c) 2022-2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Tim Moon's avatar
Tim Moon committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 *
 * See LICENSE for license information.
 ************************************************************************/

#include <cstdint>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <string>

#include "../common.h"
#include "../util/system.h"

namespace transformer_engine {

namespace {

template <typename T>
inline typename std::enable_if<std::is_arithmetic<T>::value, T>::type
23
getenv_helper(const char *variable, const T &default_value) {
Tim Moon's avatar
Tim Moon committed
24
  // Implementation for numeric types
25
  const char *env = std::getenv(variable);
Tim Moon's avatar
Tim Moon committed
26
27
28
29
30
31
32
33
34
35
36
37
  if (env == nullptr || env[0] == '\0') {
    return default_value;
  }
  T value;
  std::istringstream iss(env);
  iss >> value;
  NVTE_CHECK(iss, "Invalid environment variable value");
  return value;
}

template <typename T>
inline typename std::enable_if<!std::is_arithmetic<T>::value, T>::type
38
getenv_helper(const char *variable, const T &default_value) {
Tim Moon's avatar
Tim Moon committed
39
  // Implementation for string-like types
40
  const char *env = std::getenv(variable);
Tim Moon's avatar
Tim Moon committed
41
42
43
44
45
46
47
48
49
  if (env == nullptr || env[0] == '\0') {
    return default_value;
  } else {
    return env;
  }
}

}  // namespace

50
51
52
53
54
55
56
#define NVTE_INSTANTIATE_GETENV(T, default_value)          \
  template <> T getenv<T>(const char *variable,            \
                          const T &default_value_) {       \
    return getenv_helper<T>(variable, default_value_);     \
  }                                                        \
  template <> T getenv<T>(const char *variable) {          \
    return getenv_helper<T>(variable, default_value);      \
Tim Moon's avatar
Tim Moon committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  }
NVTE_INSTANTIATE_GETENV(bool, false);
NVTE_INSTANTIATE_GETENV(float, 0.f);
NVTE_INSTANTIATE_GETENV(double, 0.);
NVTE_INSTANTIATE_GETENV(int8_t, 0);
NVTE_INSTANTIATE_GETENV(int16_t, 0);
NVTE_INSTANTIATE_GETENV(int32_t, 0);
NVTE_INSTANTIATE_GETENV(int64_t, 0);
NVTE_INSTANTIATE_GETENV(uint8_t, 0);
NVTE_INSTANTIATE_GETENV(uint16_t, 0);
NVTE_INSTANTIATE_GETENV(uint32_t, 0);
NVTE_INSTANTIATE_GETENV(uint64_t, 0);
NVTE_INSTANTIATE_GETENV(std::string, std::string());
NVTE_INSTANTIATE_GETENV(std::filesystem::path, std::filesystem::path());

bool file_exists(const std::string &path) {
  return static_cast<bool>(std::ifstream(path.c_str()));
}

}  // namespace transformer_engine