env.h 956 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #pragma once
  2. #include <c10/util/Exception.h>
  3. #include <c10/util/Optional.h>
  4. #include <cstring>
  5. namespace c10 {
  6. namespace utils {
  7. // Reads an environment variable and returns
  8. // - optional<true>, if set equal to "1"
  9. // - optional<false>, if set equal to "0"
  10. // - nullopt, otherwise
  11. //
  12. // NB:
  13. // Issues a warning if the value of the environment variable is not 0 or 1.
  14. inline optional<bool> check_env(const char* name) {
  15. #ifdef _MSC_VER
  16. #pragma warning(push)
  17. #pragma warning(disable : 4996)
  18. #endif
  19. auto envar = std::getenv(name);
  20. #ifdef _MSC_VER
  21. #pragma warning(pop)
  22. #endif
  23. if (envar) {
  24. if (strcmp(envar, "0") == 0) {
  25. return false;
  26. }
  27. if (strcmp(envar, "1") == 0) {
  28. return true;
  29. }
  30. TORCH_WARN(
  31. "Ignoring invalid value for boolean flag ",
  32. name,
  33. ": ",
  34. envar,
  35. "valid values are 0 or 1.");
  36. }
  37. return c10::nullopt;
  38. }
  39. } // namespace utils
  40. } // namespace c10