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