Tpetra parallel linear algebra  Version of the Day
Tpetra_Details_Environment.cpp
1 #include <cstdlib>
2 #include <string>
3 #include <iostream>
4 #include <algorithm>
5 
6 #include "Tpetra_Details_Environment.hpp"
7 
8 using Tpetra::Details::Environment;
9 
10 void Environment::cacheVariable(const std::string& variableName,
11  const char* variableValue) {
12  // Cache the environment variable
13  environCache_[variableName] = variableValue;
14 }
15 
16 bool Environment::variableExists(const std::string& variableName) {
17  // Check if variable is in the cache
18  if (environCache_.find(variableName) != environCache_.end()) {
19  // variableName is cached
20  return environCache_[variableName] != NULL;
21  } else {
22  // Variable has not been cached
23  const char* variableValue = std::getenv(variableName.c_str());
24  cacheVariable(variableName, variableValue);
25  return variableValue != NULL;
26  }
27 }
28 
29 bool Environment::variableIsCached(const std::string& variableName) {
30  // Check if variable is in the cache
31  if (environCache_.find(variableName) != environCache_.end()) {
32  return true;
33  } else {
34  // Variable has not been cached
35  return false;
36  }
37 }
38 
39 bool Environment::getBooleanValue(const std::string& variableName,
40  const std::string& defaultValue) {
41  // Get the value of the environment variable variableName.
42  std::string variableValue(getValue(variableName, defaultValue));
43  std::transform(variableValue.begin(), variableValue.end(),
44  variableValue.begin(), ::toupper);
45 
46  if (variableValue.empty() ||
47  variableValue == "0" ||
48  variableValue == "NO" ||
49  variableValue == "FALSE") {
50  return false;
51  } else {
52  return true;
53  }
54 }
55 
56 std::string Environment::getValue(const std::string& variableName,
57  const std::string& defaultValue) {
58  // Get the value of the environment variable variableName.
59  const char* tmpValue;
60  if (variableExists(variableName)) {
61  tmpValue = environCache_[variableName];
62  } else {
63  // First time encountering this variable, get it from the system and cache
64  // it
65  tmpValue = std::getenv(variableName.c_str());
66  cacheVariable(variableName, tmpValue);
67  }
68 
69  std::string variableValue;
70  if (tmpValue != NULL) {
71  variableValue = std::string(tmpValue);
72  } else {
73  // Initialize variableValue to the default
74  variableValue = defaultValue;
75  }
76  return variableValue;
77 }
78 
79 // void Environment::setValue(const std::string& variableName,
80 // const std::string& variableValue,
81 // const int overwrite) {
82 // // Set the environment variable
83 // bool exists = variableExists(variableName);
84 // if ((exists && overwrite) || (!exists)) {
85 // const char* tmpValue(variableValue.c_str());
86 // environCache_[variableName] = tmpValue;
87 // setenv(variableName.c_str(), variableValue.c_str(), 1);
88 // }
89 // }
90 
91 void Environment::clearCache() {
92  environCache_.clear();
93 }