env.h 944 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #pragma once
  2. #include <c10/util/Exception.h>
  3. #include <cstdlib>
  4. #include <cstring>
  5. #include <optional>
  6. namespace c10::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 std::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 std::nullopt;
  38. }
  39. } // namespace c10::utils